SpringMVC RequestMapping 詳解


SpringMVC RequestMapping 詳解

RequestMapping這個注解在SpringMVC扮演着非常重要的角色,可以說是隨處可見。它的知識點很簡單。今天我們就一起學習SpringMVC的RequestMapping這個注解。文章主要分為兩個部分:RequestMapping 基礎用法和RequestMapping 提升用法。

准備工作

pom.xml 這里是需要的jar包和相關的配置。這里設置了maven-compiler-plugin的java版本為1.7,避免打包出錯和中文亂碼的問題。

<?xml version="1.0" encoding="UTF-8"?>  
<project xmlns="http://maven.apache.org/POM/4.0.0"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>com.springmvc</groupId>  
  <artifactId>springmvc</artifactId>  
  <version>0.0.1-SNAPSHOT</version>  
  <packaging>war</packaging>  
    
  <!-- 若不配置,打包時會提示錯誤信息   
    Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project springmvc: Compilation failure:  
    提示 未結束的字符串文字 ,若字符串后面加上空格后可以打包成功,但會亂碼。  
    原因是:maven使用的是默認的compile插件來進行編譯的。complier是maven的核心插件之一,然而complier插件默認只支持編譯Java 1.4  
    -->  
  <build>  
    <plugins>  
        <plugin>  
            <artifactId>maven-compiler-plugin</artifactId>  
            <configuration>  
                <source>1.7</source>  
                <target>1.7</target>  
                <encoding>UTF-8</encoding>  
            </configuration>  
        </plugin>  
    </plugins>  
  </build>  
    
  <properties>    
    <spring.version>4.1.3.RELEASE</spring.version>    
  </properties>   
  <dependencies>  
    <!-- spring begin -->    
    <dependency>    
        <groupId>org.springframework</groupId>    
        <artifactId>spring-webmvc</artifactId>    
        <version>${spring.version}</version>    
    </dependency>    
    
    <dependency>    
        <groupId>org.springframework</groupId>    
        <artifactId>spring-context</artifactId>    
        <version>${spring.version}</version>    
    </dependency>    
    
    <dependency>    
        <groupId>org.springframework</groupId>    
        <artifactId>spring-aop</artifactId>    
        <version>${spring.version}</version>    
    </dependency>    
    
    <dependency>    
        <groupId>org.springframework</groupId>    
        <artifactId>spring-core</artifactId>    
        <version>${spring.version}</version>    
    </dependency>   
       
    <dependency>    
        <groupId>org.springframework</groupId>    
        <artifactId>spring-web</artifactId>    
        <version>${spring.version}</version>    
    </dependency>    
    
    <!-- spring end -->  
    <dependency>  
        <groupId>javax.servlet</groupId>  
        <artifactId>javax.servlet-api</artifactId>  
        <version>4.0.0</version>  
        <scope>provided</scope>  
    </dependency>  
      
  </dependencies>   
</project>  

web.xml 設置字符攔截器,避免中文亂碼

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns="http://java.sun.com/xml/ns/javaee"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
    id="WebApp_ID" version="3.0">  
    <display-name>springmvc</display-name>  
  
    <!-- 配置 DispatcherServlet -->  
    <servlet>  
        <servlet-name>dispatcher</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <!-- 指定 SpringMVC 配置文件的位置和名稱  
            若SpringMVC的配置文件名的格式和位置滿足: /WEB-INF/servlet-name + "-servlet.xml"  
            則可以省略下面的init-param代碼。這里的servlet-name是dispatcher。 即/WEB-INF/dispatcher-servlet.xml  
        -->  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>dispatcher</servlet-name>  
        <!-- servlet知識點:處理所有請求 -->  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
      
    <!-- 字符集過濾器 -->    
    <filter>    
        <filter-name>encodingFilter</filter-name>    
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>    
        <init-param>    
            <param-name>encoding</param-name>    
            <param-value>UTF-8</param-value>    
        </init-param>    
        <init-param>    
            <param-name>forceEncoding</param-name>    
            <param-value>true</param-value>    
        </init-param>    
    </filter>    
    <filter-mapping>    
        <filter-name>encodingFilter</filter-name>    
        <url-pattern>/*</url-pattern>    
    </filter-mapping>  
      
</web-app>  

SpringMVC的配置文件(dispatcher-servlet.xml)沒有變,這里就不再貼出來了。可以去上一章找

RequestMapping 基礎用法

核心類 ApiStudyController,這是重點需要看的java文件。里面主要介紹了@RequestMapping 的基礎用法。
你需要重點學習的有: 獲取請求參數值的@RequestParam注解;通過占位符獲取參數值的@PathVariable注解;指定請求方式的method屬性;用於將數據存儲到作用域中返回給前端的Map,Model和ModelMap參數;以及如何使用POJO對象作為方法的參數。

import java.util.Map;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.ui.ModelMap;  
import org.springframework.web.bind.annotation.CookieValue;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestHeader;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.RequestParam;  
  
@Controller  
@RequestMapping("apiStudy")  
public class ApiStudyController {  
      
    private static final String SUCCESS = "apistudy";  
    private static final String RESULT_KEY = "result";  
      
    /** 
     * 常用知識點:在類或者方法上使用 @RequestMapping 注解 
     * 若沒有修飾類,則訪問路徑是: http://ip:port/項目名/方法的@RequestMapping值 
     * 若類有修飾類,則訪問路徑是: http://ip:port/項目名/類的@RequestMapping值/方法的@RequestMapping值 
     */  
      
    /** 
     * 方法中用map作為參數,可以將數據存儲到request作用域中,放回到頁面上。 
     * 同樣用法的有  Model 類型 和  ModelMap 類型 
     */  
    @RequestMapping("/testMapResult")  
    public String testMapResult(Map<String, Object> map, Model model, ModelMap modelMap){  
        String apiDocs = "Map,Model,ModelMap (常用方法) : 在方法中添加Map的參數,可以將數據放到request 作用域中!";   
        map.put(RESULT_KEY, apiDocs);  
        model.addAttribute("model", "Model");  
        modelMap.addAttribute("modelMap", "ModelMap");  
        return SUCCESS;  
    }  
      
    /** 
     * 常用知識點:使用 method 屬性來指定請求方式 
     * 若用GET方式請求,會提示:HTTP Status 405 - Request method 'GET' not supported 錯誤信息 
     */  
    @RequestMapping(value = "/testRequestMethod", method=RequestMethod.POST)  
    public String testRequestMethod(Map<String, Object> map) {  
        String apiDocs = "RequestMethod (常用方法) : 若設置只有POST請求才能進入,則用GET方式請求,會報405的錯誤。反之亦然!";   
        map.put(RESULT_KEY, apiDocs);  
        return SUCCESS;  
    }  
      
    /** 
     * 常用知識點:使用注解 @PathVariable 映射 URL綁定占位,屬於REST風格。 
     * 注意兩點: 
     * 1. 嚴格用法: @PathVariable("arg") String arg; 前一個arg參數,必須要和占位參數{arg}保持一致。后面一個arg參數可以自定義。 
     * 2. 偷懶用法: @PathVariable String arg; 這里的參數名 arg 必須要和占位參數{arg}保持一致,不然會提示400的錯誤 
     */  
    @RequestMapping("/testPathVariable/{arg}")  
    public String testPathVariable(@PathVariable("arg") String arg, Map<String, Object> map) {  
        String apiDocs = "PathVariable (常用方法) : 通過映射 URL綁定占位獲取的值是 " + arg;  
        map.put(RESULT_KEY, apiDocs);  
        return SUCCESS;  
    }  
      
    /** 
     * 常用知識點:使用注解 @RequestParam 來映射請求參數 
     * 該注解有三個參數, 
     * value 請求的參數名,  
     * required 請求的參數是否必填 ,默認是true,  
     * defaultValue 請求的參數默認值. 
     * 參數的類型建議是封裝數據類型,因為float默認值是0.0 ,若該參數是非必填,則會報錯 HTTP Status 500 
     */  
    @RequestMapping("/testRequestParam")  
    public String testRequestParam(@RequestParam("account") String account,  
            @RequestParam(value="password", required=true) String password,  
            @RequestParam(value="price", required=false, defaultValue="0.0") float price,  
            Map<String, Object> map) {  
        String apiDocs = "RequestParam (常用方法) : 獲取映射請求參數的值有 account : " + account + " password : " + password + " price : " + price;  
        map.put(RESULT_KEY, apiDocs);  
        return SUCCESS;  
    }  
      
    /** 
     * 常用知識點:方法參數是POJO對象 
     * 前端的請求參數名一定要和POJO對象屬性一致。支持級聯 
     */  
    @RequestMapping(value = "/testPojo", method = RequestMethod.POST)  
    public String testPojo(User user, Map<String, Object> map) {  
        map.put(RESULT_KEY, user);  
        return SUCCESS;  
    }  
      
    /** 
     * 不常用方法:params 和 headers 
     * @RequestMapping 注解中,除了常用的value和method外,還有兩個較為常用的params和headers 
     * 他們可以是請求跟精確,制定那些參數的請求不接受,同時也可以指定那些參數的請求接收。 
     * params={param1,param2} 
     * param1 表示 請求必須包含名為param1的請求參數 
     * !param1 表示 請求不能包含名為param1的請求參數 
     * param1!=value1 表示請求包含param1的請求參數,但是其值不能是value1 
     */  
    @RequestMapping(value="/testParamsAndHeaders", params={"itdragon"},   
            headers = { "Accept-Language=zh-CN,zh;q=0.8" })  
    public String testParamsAndHeaders(Map<String, Object> map) {  
        String apiDocs = "params,headers (了解用法) : 這里表示當請求參數中包含了itdragon的時候才能進來";  
        map.put(RESULT_KEY, apiDocs);  
        return SUCCESS;  
    }  
      
    /** 
     * 不常用方法:ant風格 
     * ?匹文件名中一個字  
     * *匹文件名中任意字  
     * ** 匹多 層徑 
     */  
    @RequestMapping("/*/testAntUrl")  
    public String testAntUrl(Map<String, Object> map) {  
        String apiDocs = "Ant風格 (了解用法) : ?匹文件名中一個字 ; *匹文件名中任意字 ; ** 匹多 層徑 ";  
        map.put(RESULT_KEY, apiDocs);  
        return SUCCESS;  
    }  
      
    /**  
     * 不常用方法:@RequestHeader 注解獲取請求頭數據。  
     */  
    @RequestMapping("/testRequestHeader")  
    public String testRequestHeader(@RequestHeader(value = "Accept-Language") String al,  
            Map<String, Object> map) {  
        String apiDocs = "@RequestHeader (了解用法) : 獲取請求頭數據的注解, 如Accept-Language 的值是 : " + al;  
        map.put(RESULT_KEY, apiDocs);  
        return SUCCESS;  
    }  
      
    /** 
     * 不常用方法:@CookieValue: 映射一個 Cookie值 
     */  
    @RequestMapping("/testCookieValue")  
    public String testCookieValue(@CookieValue("JSESSIONID") String sessionId,  
            Map<String, Object> map) {  
        String apiDocs = "@CookieValue(了解用法) : 映射一個 Cookie值的注解, 如JSESSIONID 的Cookie值是 : " + sessionId;  
        map.put(RESULT_KEY, apiDocs);  
        return SUCCESS;  
    }  
}  

用於測試的前端頁面 index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<!DOCTYPE html>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>SpringMVC 快速入門</title>  
</head>  
<body>  
  
    <h2>@RequestMapping 注解基本用法</h2>  
    <a href="helloworld">史上最丑的HelloWorld</a>  
    <br/><br/>  
    <a href="apiStudy/testMapResult">Map,Model,ModelMap的使用方法</a>  
    <br/><br/>  
    <a href="apiStudy/testRequestMethod">用GET請求方式測試POST方法</a>  
    <form action="apiStudy/testRequestMethod" method="POST">  
        <input type="submit" value="用POST請求方式測試POST方法"/>  
    </form>  
    <br/>  
    <a href="apiStudy/testPathVariable/itdragon">@PathVariable獲取占位數據</a>  
    <br/><br/>  
    <a href="apiStudy/testRequestParam?account=itdragon&password=123456">@RequestParam獲取請求參數值</a>  
    <br/><br/>  
    <form action="apiStudy/testPojo" method="post">  
        account: <input type="text" name="account" value="itdragon"/> <br>  
        level: <input type="text" name="position.level" value="架構師"/> <br>  
        salary: <input type="text" name="position.salary" value="88888.88"/> <br>  
        <input type="submit" value="測試方法參數是POJO"/>  
    </form>  
    <br/>  
    <hr/>  
    <a href="apiStudy/testParamsAndHeaders?itdragon=great">params 和 headers用法</a>  
    <br/><br/>  
    <a href="apiStudy/itdragon/testAntUrl">Ant風格URL請求</a>  
    <br/><br/>  
    <a href="apiStudy/testRequestHeader">@RequestHeader 注解獲取請求頭數據</a>  
    <br/><br/>  
    <a href="apiStudy/testCookieValue">@CookieValue 注解獲取 Cookie值</a>  
</body>  
</html>  

方便查看結果的apistudy.jsp頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<!DOCTYPE html>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>SpringMVC 快速入門</title>  
</head>  
<body>  
  
    <h2>@RequestMapping 注解基本用法</h2>  
    request 作用域 : <br/>  
    ${requestScope.result} <br/>  
    ${requestScope.model} <br/>  
    ${requestScope.modelMap} <br/>  
      
    <hr/>  
      
    session 作用域 : <br/>  
    ${sessionScope.result}  
</body>  
</html>  

最后是兩個用於測試的POJO對象,分別是User和Position

public class User {  
      
    private Integer id;  
    private String account;  
    private String password;  
    private Position position;  
      
    public User() {  
    }  
    public User(Integer id, String account, String password) {  
        this.id = id;  
        this.account = account;  
        this.password = password;  
    }  
    public Integer getId() {  
        return id;  
    }  
    public void setId(Integer id) {  
        this.id = id;  
    }  
    public String getAccount() {  
        return account;  
    }  
    public void setAccount(String account) {  
        this.account = account;  
    }  
    public String getPassword() {  
        return password;  
    }  
    public void setPassword(String password) {  
        this.password = password;  
    }  
    public Position getPosition() {  
        return position;  
    }  
    public void setPosition(Position position) {  
        this.position = position;  
    }  
    @Override  
    public String toString() {  
        return "User [id=" + id + ", account=" + account + ", password=" + password + ", position="  
                + position + "]";  
    }  
  
}  
public class Position {  
      
    private Integer id;  
    private String level;  
    private Double salary;  
    public Integer getId() {  
        return id;  
    }  
    public void setId(Integer id) {  
        this.id = id;  
    }  
    public String getLevel() {  
        return level;  
    }  
    public void setLevel(String level) {  
        this.level = level;  
    }  
    public Double getSalary() {  
        return salary;  
    }  
    public void setSalary(Double salary) {  
        this.salary = salary;  
    }  
    @Override  
    public String toString() {  
        return "Position [level=" + level + ", salary=" + salary  
                + "]";  
    }  
      
} 

測試的效果圖

RequestMapping 提升用法

這里的知識點有:輸出模型數據 ModelAndView類型,Map(Model,ModelMap),@ModelAttribute注解,@SessionAttributes注解的使用,和 原生的Servlet Api的使用。
ModelAndView數據類型:見名知意,即包含了模型數據,又包含了視圖數據。設置模型數據有兩種方式:modelAndView.addObject(String attributeName, Object attributeValue) 方分別表示Key和Value。modelAndView.addAllObjects(modelMap) 存的參數是一個Map(Model,ModelMap其實都是Map數據類型)。
設置視圖數據常用方法也有兩種方式:
ModelAndView modelAndView = new ModelAndView(viewName) 初始化ModelAndView的時候設置。
modelAndView.setViewName(viewName) 初始化后再she'zh
@ModelAttribute 注解:被該注解修飾的方法, 會在每個目標方法執行之前被 SpringMVC 調用。實際開發中其實用的並不是很多。在我們更新數據的時候,一般都會先查詢,后更新。該注解就扮演督促查詢的角色,在執行更新的方法前先執行該注解修飾的查詢數據方法。
@SessionAttributes 注解:只能修飾在類上,將模型數據暫存到HttpSession中,從而使多個請求的數據共享。常用方法有@SessionAttributes(value={"obj1", "obj2"}, types={String.class, Obj1.class})。表示可以將數據類型是String或者是對象Obj1的模型數據放到HttpSession中。也可以將變量名是obj1,obj2的模型數據放到HttpSession中。用這個注解容易出一個問題。HttpSessionRequiredException 異常,原因在代碼注釋中。
原生的Servlet Api:如果發現不能引入javax.servlet.* 的文件,可能是因為項目里面中沒有servlet-api.jar。
普通項目解決方法:右擊項目工程名稱 ---> Build Path ---> Configure Build Path... ---> 選擇 Libraries 點擊 Add External JARS ---> 在按照tomcat的里面下,找到lib目錄,里面就有。
Maven項目解決方法:如果按照上面的方法處理,雖然引入文件,當打包的時候會提示"找不到符號",是因為servlet-api.jar 沒有真正的加入到classpath下。最簡單的方法就是在pom.xml加入servlet-api.jar。
看代碼:

import java.io.IOException;  
import java.io.Writer;  
import java.util.Map;  
  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.ModelAttribute;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestParam;  
import org.springframework.web.bind.annotation.SessionAttributes;  
import org.springframework.web.servlet.ModelAndView;  
  
@Controller  
@RequestMapping("apiStudy")  
@SessionAttributes(value={"user"}, types={String.class})  
public class ApiStudyController {  
      
    private static final String SUCCESS = "apistudy";  
    private static final String RESULT_KEY = "result";  
      
    /** 
     * @SessionAttributes 將數據存儲到session中,達到多個請求數據共享的目的。 
     * 只能修飾在類上的注解 
     * 通過屬性名value,指定需要放到會話中的屬性 
     * 通過模型屬性的對象類型types,指定哪些模型屬性需要放到會話中 
     */  
      
    /** 
     * 常用方法:ModelAndView 方法的返回值設置為 ModelAndView 類型。  
     * ModelAndView 顧名思義,是包含視圖和模型信息的類型。 
     * 其數據存放在 request 域對象中.  
     */  
    @RequestMapping("/testModelAndView")  
    public ModelAndView testModelAndView() {  
        String viewName = SUCCESS; // 需要返回的視圖名  
        String apiDocs = "ModelAndView(常用方法) : 之前學習的方法返回值是字符串,數據是通過Map返回到前端。現在可以通過ModelAndView類型直接完成。";  
        ModelAndView modelAndView = new ModelAndView(viewName);  
        modelAndView.addObject(RESULT_KEY, apiDocs); // 添加數據到model中  
        return modelAndView;  
    }  
      
    /** 
     * SpringMVC 確定目標方法 POJO 類型入參的過程 
     * 第一步: 確定一個 key 
     * 若方法形如 "testModelAttribute(User user)" , 則key為 user(POJO 類名第一個字母小寫) 
     * 若方法形如"testModelAttribute(@ModelAttribute("userObj") User user)" ,則key為 userObj 
     * 第二步: 在 implicitModel 中查找 key 對應的對象 
     * 若 implicitModel 存在, 則作為入參傳入 
     * 若 implicitModel 中不存在, 則檢查當前Handler 是否使用 @SessionAttributes 注解 
     *      若使用了該注解, 且 @SessionAttributes 注解的 value 屬性值中包含了 key, 則會從 HttpSession 中來獲取 key 所對應的 value 值, 若存在則直接傳入到目標方法的入參中. 若不存在則將拋出異常.  
     *      若 Handler 沒有標識 @SessionAttributes 注解或 @SessionAttributes 注解的 value 值中不包含 key, 則通過反射來創建 POJO 類型的參數, 傳入為目標方法的參數 
     * implicitModel?  SpringMVC 會把 key 和 POJO 類型的對象保存到 implicitModel 中, 進而會保存到 request 中.  
     */  
    @RequestMapping("/testModelAttribute")  
    public ModelAndView testModelAttribute(User user){  
        ModelAndView modelAndView = new ModelAndView(SUCCESS);  
        modelAndView.addObject(RESULT_KEY, "update : " + user); // 添加數據到model中  
        return modelAndView;  
    }  
      
    /** 
     * 常用方法:@ModelAttribute 修飾方法。 被該注解修飾的方法, 會在每個目標方法執行之前被 SpringMVC 調用 
     * 運行流程: 
     * 第一步: 在執行 testModelAttribute(User user) 方法前,會先執行被@ModelAttribute 注解修飾的方法 getUser() 
     * 第二步: 執行getUser() 后,將執行放入到Map中,其中的key 必須和目標方法User對象的首字母小寫user 
     * 第三步: SpringMVC 從 Map 中取出 User 對象,然后把對象傳入目標方法的參數.  
     *  
     * 未使用 @ModelAttribute testModelAttribute方法 打印的信息 :  
     * update : User [id=1, account=itdragon, password=null, position=null]  
     * 使用@ModelAttribute testModelAttribute方法 打印的信息 :  
     * update : User [id=1, account=itdragon, password=zhangdeshuai, position=null]  
     */  
    @ModelAttribute  
    public void getUser(@RequestParam(value="id",required=false) Integer id,   
            Map<String, Object> map){  
        if(id != null){  
            //模擬從數據庫中獲取對象  
            User user = new User(1, "itdragon", "zhangdeshuai");  
            map.put("user", user); // 這里的key 一定是該對象User的首字母小寫user  
        }  
    }  
      
    /** 
     * 常用方法:可以使用 Serlvet 原生的 API 作為目標方法的參數 具體支持以下類型 
     *  
     * HttpServletRequest  
     * HttpServletResponse  
     * HttpSession 
     * InputStream  
     * OutputStream  
     * Reader  
     * Writer 
     */  
    @RequestMapping("/testServletAPI")  
    public void testServletAPI(HttpServletRequest request,  
            HttpServletResponse response, Writer out) throws IOException {  
        response.setCharacterEncoding("utf-8");  
        response.setContentType("text/html;charset=utf-8");  
        out.write("Hello Servlet API,和用Servlet一樣(0——0) ; <br/>request : " + request + " ;<br/>response : " + response);  
    }  
      
}  

一樣的前端index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<!DOCTYPE html>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>SpringMVC 快速入門</title>  
</head>  
<body>  
  
    <h2>@RequestMapping 注解提升用法</h2>  
    <a href="apiStudy/testModelAndView">ModelAndView的使用方法</a>  
    <br/><br/>  
    <form action="apiStudy/testModelAttribute" method="post">  
        <input type="hidden" name="id" value="1"/><!-- 隱藏域 id -->  
        account: <input type="text" name="account" value="itdragon"/> <br>  
        <input type="submit" value="testModelAttribute"/>  
    </form>  
    <br/>  
    <a href="apiStudy/testServletAPI">使用原生的Servlet API</a>  
    <br/><br/>  
</body>  
</html>  

兩個實體類和查看結果的jsp頁面沒有變
效果圖:



Spring MVC 其實提供了很多的組合注解:
@RestController = @Controller + @ResponseBody
@GetMapping = @RequestMapping(method = { RequestMethod.GET })
@PostMapping = @RequestMapping(method = { RequestMethod.POST })
后續有時間會補充,留着備忘!

補充,由於springMVC默認認為/users 和 /users.* 匹配規則等價,若不希望這樣可以設置為false。

/**
 * Whether to use suffix pattern match (".*") when matching patterns to
 * requests. If enabled a method mapped to "/users" also matches to "/users.*".
 * <p>By default this is set to {@code true}.
 * @see #registeredSuffixPatternMatch
 */
public PathMatchConfigurer setUseSuffixPatternMatch(Boolean suffixPatternMatch) {
	this.suffixPatternMatch = suffixPatternMatch;
	return this;
}	    

需要配置

override fun configurePathMatch(configurer: PathMatchConfigurer) {
	configurer.setUseSuffixPatternMatch(false)
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM