SpringMVC——RequestMapping

來源:互聯網
上載者:User

標籤:支援   locale   protect   default   設定   表達   過程   def   except   

一、@RequestMapping 映射請求 

Spring MVC 通過@RequestMapping註解可以定義不同的處理器映射規則。

  • @RequestMapping放在類名上邊,佈建要求首碼
  • 方法名上邊佈建要求映射url

二、映射請求參數、要求方法或要求標頭

@RequestMapping 除了可以使用請求 URL 對應請求外, 還可以使用要求方法、請求參數及要求標頭映射請求

  1、@RequestMapping 的 value、method、params 及 heads 分別表示請求 URL、要求方法、請求參數及要求標頭的映射條件,他們之間是與的關係,聯合使用多個條件可讓請求映射 更加精確化。

  /**     * 常用: 使用 method 屬性來指定請求方式     */    @RequestMapping(value = "/testMethod", method = RequestMethod.POST)    public String testMethod() {        System.out.println("testMethod");        return SUCCESS;    }

  2、params 和 headers支援簡單的運算式:

  • param1: 表示請求必須包含名為 param1 的請求參數
  • !param1: 表示請求不能包含名為 param1 的請求參數
  • param1 != value1: 表示請求包含名為 param1 的請求參數,但其值 不能為 value1
  • {“param1=value1”, “param2”}: 請求必須包含名為 param1 和param2 的兩個請求參數,且 param1 參數的值必須為 value1
  /**     * 可以使用 params 和 headers 來更加精確的映射請求. 
   * 請求中必須包含username請求參數,age請求參數的值不能等於10
*/ @RequestMapping(value = "testParamsAndHeaders", params = { "username", "age!=10" }, headers = { "Accept-Language=en-US,zh;q=0.8" }) public String testParamsAndHeaders() { System.out.println("testParamsAndHeaders"); return SUCCESS; }
三、@PathVariable 映射 URL 綁定的預留位置 
  • 帶預留位置的 URL 是 Spring3.0 新增的功能,該功能在 SpringMVC 向 REST 目標挺進發展過程中具有裡程碑的意義
  • 通過 @PathVariable 可以將 URL 中預留位置參數綁定到控制器處理方法的入參中:URL 中的 {xxx} 預留位置可以通過 @PathVariable("xxx") 綁定到操作方法的入參中。
    /**     * @PathVariable 可以來映射 URL 中的預留位置到目標方法的參數中.     * @param id     * @return     */    @RequestMapping("/testPathVariable/{id}")    public String testPathVariable(@PathVariable("id") Integer id) {        System.out.println(id);        return SUCCESS;    }    
四、HiddenHttpMethodFilter:

  瀏覽器 form 表單只支援 GET 與 POST 請求,而DELETE、PUT 等 method 並不支 持,Spring3.0 添加了一個過濾器,可以將這些請求轉換 為標準的 http 方法,使得支援 GET、POST、PUT 與 DELETE 請求。

如何發送 PUT 請求和 DELETE 請求呢 ?
  1. 需要配置 HiddenHttpMethodFilter

  <!--    配置 org.springframework.web.filter.HiddenHttpMethodFilter: 可以把 POST 請求轉為 DELETE 或 POST 請求    -->    <filter>        <filter-name>HiddenHttpMethodFilter</filter-name>        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>HiddenHttpMethodFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>
//// Source code recreated from a .class file by IntelliJ IDEA// (powered by Fernflower decompiler)//package org.springframework.web.filter;import java.io.IOException;import java.util.Locale;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;import javax.servlet.http.HttpServletResponse;import org.springframework.util.Assert;import org.springframework.util.StringUtils;import org.springframework.web.filter.OncePerRequestFilter;public class HiddenHttpMethodFilter extends OncePerRequestFilter {    public static final String DEFAULT_METHOD_PARAM = "_method";    private String methodParam = "_method";    public HiddenHttpMethodFilter() {    }    public void setMethodParam(String methodParam) {        Assert.hasText(methodParam, "\‘methodParam\‘ must not be empty");        this.methodParam = methodParam;    }    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {        String paramValue = request.getParameter(this.methodParam);        if("POST".equals(request.getMethod()) && StringUtils.hasLength(paramValue)) {            String method = paramValue.toUpperCase(Locale.ENGLISH);            HiddenHttpMethodFilter.HttpMethodRequestWrapper wrapper = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, method);            filterChain.doFilter(wrapper, response);        } else {            filterChain.doFilter(request, response);        }    }    private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {        private final String method;        public HttpMethodRequestWrapper(HttpServletRequest request, String method) {            super(request);            this.method = method;        }        public String getMethod() {            return this.method;        }    }}

  2.需要在發送 POST 請求時攜帶一個 name="_method" 的隱藏欄位, 值為 DELETE 或 PUT

    <form action="springmvc/testRest/1" method="post">        <input type="hidden" name="_method" value="PUT"/>        <input type="submit" value="TestRest PUT"/>    </form>        <form action="springmvc/testRest/1" method="post">        <input type="hidden" name="_method" value="DELETE"/>        <input type="submit" value="TestRest DELETE"/>    </form>        <form action="springmvc/testRest" method="post">        <input type="submit" value="TestRest POST"/>    </form>        <a href="springmvc/testRest/1">Test Rest Get</a>

  [email protected]添加method屬性

  @RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)    public String testRestPut(@PathVariable Integer id) {        System.out.println("testRest Put: " + id);        return SUCCESS;    }    @RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)    public String testRestDelete(@PathVariable Integer id) {        System.out.println("testRest Delete: " + id);        return SUCCESS;    }    @RequestMapping(value = "/testRest", method = RequestMethod.POST)    public String testRest() {        System.out.println("testRest POST");        return SUCCESS;    }    @RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET)    public String testRest(@PathVariable Integer id) {        System.out.println("testRest GET: " + id);        return SUCCESS;    }

SpringMVC——RequestMapping

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.