一、方法一:實作Controller介面
這個在我的第一個SpringMVC程式中已經學習過了,在此不作贅述,現在主要來學習第二種方法,使用注解開發;
二、方法二:使用注解開發
1.導包
2.在web.xml中配置DispatcherServlet
3.建立一個Spring組態檔springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--掃描包,使其下的注解生效--> <context:component-scan base-package="com.jms.controller"/> <!--讓springMVC不處理靜態資源--> <mvc:default-servlet-handler/> <!-- 支持MVC注解驅動 能夠幫助我們完成BeanNameUrlHandlerMapping和SimpleControllerHandlerAdapter注入 --> <mvc:annotation-driven/> <!--視圖決議器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver"> <!--前綴--> <property name="prefix" value="/WEB-INF/jsp/"/> <!--后綴--> <property name="suffix" value=".jsp"/> </bean> </beans>
4.建立一個HelloController類
package com.jms.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { @RequestMapping("/hello") public String hello(Model model) { model.addAttribute("message", "歡迎來到SpringMVC"); return "hello"; } }
可以看到,在這個類中,我們使用到了兩種注解,
第一個是@Controller,使用這個注解就說明這個類是一個Handler;第二個是@RequestMapping,看名字就知道這是請求的映射,也就是我們需要請求的路徑,這里是請求.../hello,
可以看見一個回傳String的方法,回傳的這個hello就說明跳轉的路徑是視圖決議器中的“前綴”+hello+“后綴”,在這里也就是/WEB-INF/jsp/hello.jsp,
這里我們用一個model來存盤資料,
5.啟動tomcat測驗

(本文僅作個人學習記錄用,如有紕漏敬請指正)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/516283.html
標籤:Java
