SpringMVC RequestMapping & 請求參數

來源:互聯網
上載者:User

標籤:

SpringMVC 概述

  Spring 為展現層提供的基於 MVC 設計理念的優秀的Web 架構,是目前最主流的 MVC 架構之一
  Spring3.0 後全面超越 Struts2,成為最優秀的 MVC 架構
  Spring MVC 通過一套 MVC 註解,讓 POJO 成為處理請求的控制器,而無須實現任何介面。
  支援 REST 風格的 URL 請求
  採用了鬆散耦合可插拔組件結構,比其他 MVC 架構更具擴充性和靈活性

HelloWorld

步驟:
  –加入 jar 包
  –在 web.xml 中配置 DispatcherServlet

<!-- 實際上也可以不通過 contextConfigLocation 來配置 SpringMVC 的設定檔, 而使用預設的.預設的設定檔為: /WEB-INF/<servlet-name>-servlet.xml-->

  –加入 Spring MVC 的設定檔

<!-- 配置自定掃描的包 --><context:component-scan base-package="com.atguigu.springmvc"></context:component-scan><!-- 配置視圖解析器: 如何把 handler 方法傳回值解析為實際的物理視圖 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/views/"></property><property name="suffix" value=".jsp"></property></bean>

  –編寫處理請求的處理器,並標識為處理器

 1 @Controller 2 public class HelloWorld { 3     /** 4      * 1. 使用 @RequestMapping 註解來映射請求的 URL 5      * 2. 傳回值會通過視圖解析器解析為實際的物理視圖, 對於 InternalResourceViewResolver 視圖解析器, 會做如下的解析: 6      * 通過 prefix + returnVal + 尾碼 這樣的方式得到實際的物理視圖, 然會做轉寄操作 7      * /WEB-INF/views/success.jsp 8      */ 9     @RequestMapping("/helloworld")10     public String hello(){11         System.out.println("hello world");12         return "success";13     }14 }
helloworld.java

  –編寫視圖

@RequestMapping 映射請求

Spring MVC 使用 @RequestMapping 註解為控制器指定可以處理哪些 URL 請求

1. @RequestMapping 除了修飾方法, 還可來修飾類

  1). 類定義處: 提供初步的請求映射資訊。相對於 WEB 應用的根目錄
     2). 方法處: 提供進一步的細分映射資訊。 相對於類定義處的 URL。若類定義處未標註 @RequestMapping,則方法處標記的 URL相對於 WEB 應用的根目錄

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

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

  params 和 headers支援簡單的運算式:
    param1: 表示請求必須包含名為 param1 的請求參數
    !param1: 表示請求不能包含名為 param1 的請求參數
    param1 != value1: 表示請求包含名為 param1 的請求參數,但其值不能為 value1
    {“param1=value1”, “param2”}: 請求必須包含名為 param1 和param2 的兩個請求參數,且 param1 參數的值必須為 value1

  method取值有 RequestMethod.POST, RequestMethod.GET 等。

3. Ant 風格資源地址支援 3 種匹配符:

  ?:匹配檔案名稱中的一個字元
   *:匹配檔案名稱中的任一字元
   **: 匹配多層路徑

4. @PathVariable 可以來映射 URL 中的預留位置到目標方法的參數中.

  URL 中的 {xxx} 預留位置可以通過@PathVariable("xxx") 綁定到操作方法的入參中。

@RequestMapping("/testPathVariable/{id}")public String testPathVariable(@PathVariable("id") Integer id) {System.out.println("testPathVariable: " + id);return SUCCESS;}
 5. REST

REST:即 Representational State Transfer。(資源)表現層狀態轉化。是目前最流行的一種互連網軟體架構。它結構清晰、符合標準、易於理解、擴充方便,所以正得到越來越多網站的採用

資源(Resources):網路上的一個實體,或者說是網路上的一個具體資訊。URI 即為每一個資源的獨一無二的識別符。

表現層(Representation):把資源具體呈現出來的形式,叫做它的表現層

狀態轉化(State Transfer):每發出一個請求,就代表了用戶端和伺服器的一次互動過程。

具體說,就是 HTTP 協議裡面,四個表示操作方式的動詞:GET、POST、PUT、DELETE。它們分別對應四種基本操作:GET 用來擷取資源,POST 用來建立資源,PUT 用來更新資源,DELETE 用來刪除資源。

  樣本:
  /order/1 HTTP GET :得到 id = 1 的 order –
  /order/1 HTTP DELETE:刪除 id = 1的 order –
  /order/1 HTTP PUT:更新id = 1的 order –
  /order HTTP POST:新增 order –
HiddenHttpMethodFilter:瀏覽器 form 表單只支援 GET與 POST 請求,而DELETE、PUT 等 method 並不支援,Spring3.0 添加了一個過濾器,可以將這些請求轉換為標準的 http 方法,使得支援 GET、POST、PUT 與DELETE 請求。

 1     <!--  2     配置 org.springframework.web.filter.HiddenHttpMethodFilter: 可以把 POST 請求轉為 DELETE 或 POST 請求  3     --> 4     <filter> 5         <filter-name>HiddenHttpMethodFilter</filter-name> 6         <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 7     </filter> 8      9     <filter-mapping>10         <filter-name>HiddenHttpMethodFilter</filter-name>11         <url-pattern>/*</url-pattern>12     </filter-mapping>
web.xml
 1     <form action="springmvc/testRest/1" method="post"> 2         <input type="hidden" name="_method" value="PUT"/> 3         <input type="submit" value="TestRest PUT"/> 4     </form> 5     <br><br> 6      7     <form action="springmvc/testRest/1" method="post"> 8         <input type="hidden" name="_method" value="DELETE"/> 9         <input type="submit" value="TestRest DELETE"/>10     </form>11     <br><br>12 13     /** 14      * 如何發送 PUT 請求和 DELETE 請求呢 ? 1. 需要配置 HiddenHttpMethodFilter 2. 需要發送 POST 請求15      * 3. 需要在發送 POST 請求時攜帶一個 name="_method" 的隱藏欄位, 值為 DELETE 或 PUT16      * 17      * 在 SpringMVC 的目標方法中如何得到 id 呢? 使用 @PathVariable 註解18      * 19      */20     @RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)21     public String testRestPut(@PathVariable Integer id) {22         System.out.println("testRest Put: " + id);23         return SUCCESS;24     }25 26     @RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)27     public String testRestDelete(@PathVariable Integer id) {28         System.out.println("testRest Delete: " + id);29         return SUCCESS;30     }
example映射請求參數 & 請求參數1. 使用 @RequestParam 綁定請求參數值

 @RequestParam 來映射請求參數. value 值即請求參數的參數名, required 該參數是否必須. 預設為 true. defaultValue 請求參數的預設值

@RequestMapping(value = "/testRequestParam")public String testRequestParam(@RequestParam(value = "username") String un,@RequestParam(value = "age", required = false, defaultValue = "0") int age) {System.out.println("testRequestParam, username: " + un + ", age: " + age);return SUCCESS;}
2. 使用 @RequestHeader 綁定請求前序的屬性值
1     /**2      * 瞭解: 映射要求標頭資訊 用法同 @RequestParam3      */4     @RequestMapping("/testRequestHeader")5     public String testRequestHeader(6             @RequestHeader(value = "Accept-Language") String al) {7         System.out.println("testRequestHeader, Accept-Language: " + al);8         return SUCCESS;9     }
View Code3. 使用 @CookieValue 綁定請求中的 Cookie 值
 1     /** 2      * 瞭解: 3      *  4      * @CookieValue: 映射一個 Cookie 值. 屬性同 @RequestParam 5      */ 6     @RequestMapping("/testCookieValue") 7     public String testCookieValue(@CookieValue("JSESSIONID") String sessionId) { 8         System.out.println("testCookieValue: sessionId: " + sessionId); 9         return SUCCESS;10     }
View Code4. 使用 POJO 對象綁定請求參數值

Spring MVC 會按請求參數名和 POJO 屬性名稱進行自動匹配,自動為該對象填充屬性值。支援級聯屬性。

5. 使用 Servlet API 作為入參

具體支援以下類型: HttpServletRequest ; HttpServletResponse ;HttpSession; java.security.Principal  ; Locale InputStream ;OutputStream ;Reader ;Writer

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.