概述
Spring從2.5版本開始引入註解,雖然版本不斷變化,可是註解的特性一直被延續下來並不斷進行擴展,這裏就來記錄一下Spring MVC中經常使用的註解,本文記錄@Controller、@RequestMapping、@RequestParam和@PathVariable四個註解。
@Controller註解
該註解用來標記類,由其標記的類就是一個Spring MVC Controller的一個對象,即一個控制器類。
Spring使用掃描機制掃描應用程序中全部使用該註解進行註釋的類,分發處理器掃描使用了該註解的類的方法,檢測方法是否使用了@RequestMapping註解,使用了@RequestMapping註解的方法纔是真正處理請求的處理器。
Spring可以掃描到控制器,須要在Spring MVC的配置文件(前文例子中的springmvc-servlet.xml文件)中完成兩個配置項:
1.在頭文件中引入spring-context。
2.使用<context:component-scan/>元素,該元素的功能:啓動包掃描功能,註冊使用了@Controller、@Service、@Repository、@Component等註解的類成爲Spring的bean。
html
1 <context:component-scan base-package="com.snow.dcl.controller"/>
1 @Controller 2 @RequestMapping(value = "/user") 3 public class UserController { 4 5 @RequestMapping(value = "register") 6 public String register(){ 7 return "register"; 8 } 9 10 @RequestMapping(value = "login") 11 public String login(){ 12 return "login"; 13 } 14 } 15
由於在該類上使用了@RequestMapping(value = "/user")註解,請求都要加上/user路徑:http://localhost:8080/user/login
@RequestMapping註解支持的經常使用屬性:java
屬性 | 類型 | 說明 |
value | String[] | 用於將指定請求映射到方法上 |
method | RequestMethod[] | 映射指定請求的方法類型,包括GET、POST、PUT...... |
consumes | String[] | 指定處理請求的提交內容類型(Content-Type:application/json、text/html等) |
produces | String[] | 指定返回的內容類型,必須是request請求頭(Accept)中包含的類型 |
params | String[] | 指定request中必須包含某些參數,才讓該方法處理請求 |
header | String[] | 指定request中必須包指定的header值,才讓該方法處理請求 |
注意:因爲value是@RequestMapping註解的默認屬性,若是該註解使用時只有此一個屬性,則能夠省略改屬性名,如有多個屬性,則必須寫上value屬性名。
web
1 @RequestMapping(value = "/hello") 2 @RequestMapping("/hello")
value屬性是String[]類型,因此能夠設置多個值:
spring
1 @RequestMapping(value = {"/hello","/hello1"})
此時請求訪問兩個路徑均可以映射到同一個方法進行處理。
@RequestParam
該註解用來將指定的請求參數賦值給方法中的形參。
@RequestParam註解支持的經常使用屬性:json
屬性 | 類型 | 說明 |
name | String | 指定請求頭綁定的名稱 |
value | String | name屬性的別名 |
required | boolean | 參數是否必須綁定 |
defaultValue | String | 沒有傳遞參數時,參數的默認值 |
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 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"> 6 7 <!--spring能夠自動掃描base-package設置的包或子包下的java類,若是掃描到有spring相關注解的類,則註冊爲spring的bean--> 8 <context:component-scan base-package="com.snow.dcl.controller"/> 9 10 <!--視圖解析器--> 11 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 12 <property name="prefix"> 13 <value>/WEB-INF/content/</value> 14 </property> 15 <property name="suffix"> 16 <value>.jsp</value> 17 </property> 18 </bean> 19 20 </beans> 21
1.如今使用了註解類型,因此不須要在XML文件中描述Bean。
2.<context:component-scan base-package="com.snow.dcl.controller"/>指定Spring掃描com.snow.dcl.controller包及子包下全部的java文件。
3.而後配置視圖解析器展現,視圖解析器中配置的prefix表示視圖的前綴,suffix表示視圖的後綴。
瀏覽器
1 @RequestMapping(value = "register") 2 public String register(){ 3 return "register"; 4 }
1 @Data 2 public class User implements Serializable { 3 private String loginname; 4 private String password; 5 private String username; 6 }
1 @Controller 2 @RequestMapping(value = "/user") 3 public class UserController { 4 5 private static final Log LOGGER = LogFactory.getLog(UserController.class); 6 private static List<User> userList; 7 8 public UserController() { 9 super(); 10 userList = new ArrayList<User>(); 11 } 12 13 @RequestMapping(value = "/register", method = RequestMethod.GET) 14 public String registerForm() { 15 LOGGER.info("調用registerForm方法"); 16 return "register"; 17 } 18 19 @RequestMapping(value = "/register", method = RequestMethod.POST) 20 public String register(@RequestParam("loginname") String loginname, @RequestParam("password") String password, @RequestParam("username") String username) { 21 LOGGER.info("調用register方法"); 22 User user = new User(); 23 user.setLoginname(loginname); 24 user.setPassword(password); 25 user.setUsername(username); 26 userList.add(user); 27 return "login"; 28 } 29 30 @RequestMapping(value = "/login") 31 public String login(@RequestParam("loginname") String loginname, @RequestParam("password") String password, Model model) { 32 LOGGER.info("登陸名:" + loginname + "密碼:" + password); 33 for (User user:userList){ 34 if (user.getLoginname().equals(loginname)&&user.getPassword().equals(password)){ 35 model.addAttribute("user",user); 36 return "information"; 37 } 38 } 39 return "login"; 40 } 41 } 42
這裏使用了本文記錄的註解。
建立register.jsp文件
在項目的/WEB-INF/content目錄下建立register.jsp文件,編寫以下程序:
mvc
1 <%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> 5 <title>register</title> 6 </head> 7 <body> 8 <h3>註冊頁面</h3> 9 <br> 10 <form action="register" method="post"> 11 <table> 12 <tr> 13 <td><label>登陸名:</label></td> 14 <td><input type="text" id="loginname" name="loginname"></td> 15 </tr> 16 <tr> 17 <td><label>密碼:</label></td> 18 <td><input type="password" id="password" name="password"></td> 19 </tr> 20 <tr> 21 <td><label>用戶名:</label></td> 22 <td><input type="text" id="username" name="username"></td> 23 </tr> 24 <tr> 25 <td><input type="submit" id="submit" value="註冊"></td> 26 </tr> 27 </table> 28 </form> 29 </body>
1 <%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> 5 <title>login</title> 6 </head> 7 <body> 8 <h3>登陸頁面</h3> 9 <br> 10 <form action="login" method="post"> 11 <table> 12 <tr> 13 <td><label>登陸名:</label></td> 14 <td><input type="text" id="loginname" name="loginname"></td> 15 </tr> 16 <tr> 17 <td><label>密碼:</label></td> 18 <td><input type="password" id="password" name="password"></td> 19 </tr> 20 <tr> 21 <td><input type="submit" id="submit" value="登陸"></td> 22 </tr> 23 </table> 24 </form> 25 </body> 26 </html>
1 <%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> 5 <title>information</title> 6 </head> 7 <body> 8 <h3>歡迎"${requestScope.user.loginname}"登陸</h3> 9 <h3>用戶名爲:"${requestScope.user.username}"</h3> 10 </body> 11 </html>
1 <filter> 2 <filter-name>SetCharacterEncoding</filter-name> 3 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 4 <init-param> 5 <param-name>encoding</param-name> 6 <param-value>UTF-8</param-value> 7 </init-param> 8 <init-param> 9 <param-name>forceEncoding</param-name> 10 <param-value>true</param-value> 11 </init-param> 12 </filter> 13 <filter-mapping> 14 <filter-name>SetCharacterEncoding</filter-name> 15 <url-pattern>/*</url-pattern> 16 </filter-mapping>
不然會出現information.jsp展現的中文信息亂碼。
測試
啓動TomcatServer,啓動完成後,打開瀏覽器輸入:http://localhost:8080/user/register訪問成功。
由於此時是GET請求,調用registerForm方法,返回register.jsp。
app
填寫註冊的信息以後,發送POST請求,調用的是register方法,返回login.jsp。
填寫登陸名和密碼,調用的是login方法,進行登陸。
登錄成功後,返回information.jsp,展現信息。dom