javascript
requestmapping配置页面后_Spring MVC 入门指南(二):@RequestMapping用法详解
一、@RequestMapping?簡介
在Spring MVC 中使用 @RequestMapping 來映射請求,也就是通過它來指定控制器可以處理哪些URL請求,相當于Servlet中在web.xml中配置
servletName
ServletClass
servletName
url
的映射作用一致。讓我們先看一下RequestMapping注解類的源碼:
@Target({ElementType.METHOD,?ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public?@interface?RequestMapping?{
String?name()?default?"";
String[]?value()?default?{};
String[]?path()?default?{};
RequestMethod[]?method()?default?{};
String[]?params()?default?{};
String[]?headers()?default?{};
String[]?consumes()?default?{};
String[]?produces()?default?{};
}
2)可以看到注解中的屬性除了 name() 返回的字符串,其它的方法均返回數組,也就是可以定義多個屬性值,例如 value() 和 path() 都可以同時定義多個字符串值來接收多個URL請求
二、準備工作:(注:后面的示例都將基于準備工作)
1)新建一個 Web 工程,取名為 SpringMVC
略
2)新建一個的控制器類:UserController
package?cn.kolbe.spring.mvc.controller;
import?org.springframework.stereotype.Controller;
@Controller
public?class?UserController?{
public?String?login()?{
return?"success";
}
}
3)新建和配置 web.xml 以及 spring-mvc.xml 文件
略(具體參見 前一章:?Spring MVC 學習筆記(一):HelloWorld?)
4)新建一個測試的 JSP 頁面 index.jsp
html>
Spring?MVC?User?Login
5)新建一個成功跳轉的頁面 JSP 頁面 welcome.jsp
html>
Spring?MVCWelcome
三、測試 @RequestMapping 中的 value 和 path 屬性(這兩個屬性作用相同,可以互換,如果僅有這一個屬性,則可以省略,下面兩個例子均采用省略的方式)
1)將 @RequestMapping 注解在 login 方法上,而UserController上不添加 @RequestMapping 注解,這時的請求 URL 是相對于 Web 根目錄
@Controller
public?class?UserController?{
@RequestMapping("/login")
public?String?login()?{
return?"success";
}
}
這時的方法 login() 能處理的 URL 請求路徑是基于 Web 應用的,也就是 http://localhost/SpringMVC/login,也就是?index.jsp 頁面中的 User Login 鏈接地址應該是:
User?Login
2)將 @RequestMapping 注解在 UserController 類上,這時類的注解是相對于 Web 根目錄,而方法上的是相對于類上的路徑
@Controller
@RequestMapping("/user")
public?class?UserController?{
@RequestMapping("/login")
public?String?login()?{
return?"success";
}
}
這時的方法login()能處理的 URL 請求路徑則是 http://localhost/SpringMVC/user/login,也就是 index.jsp 頁面中的 User Login 鏈接地址應該是:
User?Login
四、測試 @RequestMapping 的 method 屬性
1)簡介:@RequestMapping 中的 method 主要用來定義接收瀏覽器發來的何種請求。在Spring中,使用枚舉類
org.springframework.web.bind.annotation.RequestMethod來定義瀏覽器請求的方式。
Http規范定義了多種請求資源的方式,最基本的有四種,分別為:GET(查)、POST(增)、PUT(改)、DELETE(刪),而URL則用于定位網絡上的資源相當于地址的作用,配合四種請求方式,可以實現對URL對應的資源的增刪改查操作。
在實際應用中,很多人并沒有按照這個規范做,因為使用GET/POST同樣可以完成PUT和DELETE操作,甚至GET也可以完成POST操作,因為GET不需要用到表單,而POST卻需要通過表單來發送。
2)通過 @RequestMapping(value="/login",method=RequestMethod.GET) 來指定 login()方法 僅處理通過 GET 方式發來的請求
@Controller
@RequestMapping(path?=?"/user")
public?class?UserController?{
@RequestMapping(path?=?"/login",?method=RequestMethod.GET)
public?String?login()?{
return?"success";
}
}
這時,如果瀏覽器發來的請求不是GET的話,將收到瀏覽器返回的錯誤提示,也就是得通過鏈接的方式而不是表單的方式:
User?Login
3)通過 @RequestMapping(value="/login",method=RequestMethod.POST) 來指定 login()方法 僅處理通過 POST 方式發來的請求
@Controller
@RequestMapping(path?=?"/user")
public?class?UserController?{
@RequestMapping(path?=?"/login",?method=RequestMethod.POST)
public?String?login()?{
return?"success";
}
}
這時,必須通過表單的方式發送請求,否則將收到瀏覽器返回的錯誤提示
4)由于在 RequestMapping 注解類中 method() 方法返回的是 RequestMethod 數組,所以可以給 method 同時指定多個請求方式,例如:
@Controller
@RequestMapping(path?=?"/user")
public?class?UserController?{
//?該方法將同時接收通過GET和POST方式發來的請求
@RequestMapping(path?=?"/login",?method={RequestMethod.POST,RequestMethod.GET})
public?String?login()?{
return?"success";
}
}
五、測試 @RequestMapping 的 params 屬性,該屬性表示請求參數,也就是追加在URL上的鍵值對,多個請求參數以&隔開,例如:
http://localhost/SpringMVC/user/login?username=kolbe&password=123456
則這個請求的參數為username=kolbe以及password=123456,@RequestMapping 中可以使用 params 來限制請求參數,來實現進一步的過濾請求,舉個例子:
@Controller
@RequestMapping(path?=?"/user")
public?class?UserController?{
//?該方法將接收?/user/login?發來的請求,且請求參數必須為?username=kolbe&password=123456
@RequestMapping(path?=?"/login",?params={"username=kolbe","password=123456"})
public?String?login()?{
return?"success";
}
}
該例中則表示 UserController 中的 login() 方法僅處理 /user/login 發來的請求,且必須帶有 username=kolbe&password=123456 的請求參數,否則瀏覽器將返回HTTP 404的錯誤, 對應 index.jsp 中的鍵接地址為:
User?Login
六、測試 @RequestMapping 的 headers 屬性,該屬性表示請求頭
用于HTTP協義交互的信息被稱為HTTP報文,客戶端發送的HTTP報文被稱為請求報文,服務器發回給客戶端的HTTP報文稱為響應報文,報文由報文頭部和報文體組成。
請求頭部(Request Headers):請求頭包含許多有關客戶端環境和請求正文的信息,例如瀏覽器支持的語言、請求的服務器地址、客戶端的操作系統等。
響應頭部(Rsponse Headers):響應頭也包含許多有用的信息,包括服務器類型、日期、響應內容的類型及編碼,響應內容的長度等等。
如果你安裝的是Chrome瀏覽器,可以通過在網頁中 ?右擊鼠標---->審查元素---->Network---->Name中點擊網頁---->右側查看Headers即可,如果Name中沒有出現網頁,可以刷新一下即可,下邊是我電腦中的一個請求頭部示例:
Request?Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,?deflate,?sdch
Accept-Language:zh-CN,zh;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Cookie:JSESSIONID=210075B5E521CWE3CDE938076295A57A
Host:localhost:8080
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0?(Macintosh;?Intel?Mac?OS?X?10_9_5)?AppleWebKit/537.36?(KHTML,?like?Gecko)?Chrome/45.0.2454.93
回規正題,通過 @RequestMapping 中的 headers 屬性,可以限制客戶端發來的請求
@Controller
@RequestMapping(path?=?"/user")
public?class?UserController?{
//?表示只接收本機發來的請求
@RequestMapping(path?=?"/login",?headers="Host=localhost:8080")
public?String?login()?{
return?"success";
}
}
七、帶占位符的URL
(一)帶占位符的URL是Spring 3.0 新增的功能,可以通過 @PathVariable 將 URL 中的占位符綁定到控制器的處理方法的參數中,占位符使用{}括起來
(二)使用方法:
1)帶占位符的URL示例:
@Controller
@RequestMapping(path?=?"/user")
public?class?UserController?{
@RequestMapping(value="/{id}",?method=RequestMethod.GET)
public?String?show(@PathVariable("id")?Integer?id)?{
return?"success";
}
}
在這個控制器中 show() 方法將可以接收 user/1、user/2、user/3等等的路徑請求,請求的方法必須為GET,使用 @PathVariable 為應用實現 REST 規范提供了具大的便利條件。
八、采用 REST 風格的 URL 請求
1)簡介:REST(Representational State Transfer):(資源)表現層狀態轉化,它是目前最流行的一種軟件架構,其結構清晰、易于理解、擴展方便且符合標準,正在越來越多的被實踐到應用中。
2)REST 風格的 URL 請求
請求路徑????????請求方法???????????作用
-/user/1????????HTTP?GET????????得到id為1的user
-/user/1????????HTTP?DELETE?????刪除id為1的user
-/user/1????????HTTP?PUT????????更新id為1的user
-/user??????????HTTP?POST???????新增user
3)由于瀏覽器表單只支持 GET 和 POST 請求,為了實現 DELETE 和 PUT 請求,Spring 為我們提供了一個過濾器org.springframework.web.filter.HiddenHttpMethodFilter,可以為我們將 GET 和 POST 請求通過過濾器轉化成 DELETE 和 PUT 請求。
4)在 web.xml 中配置過濾器
hiddenHttpMethodFilter
org.springframework.web.filter.HiddenHttpMethodFilter
hiddenHttpMethodFilter
/*
5)由于瀏覽器表單無法發送 DELETE 和 PUT 請求,所以為了讓 HiddenHttpMethodFilter 識別請求的方法,需要在表單中添加一個隱藏域,名字為 _method 值為 DELETE 或 POST 或PUT,修改后 index.jsp 頁面代碼如下:
html>
Spring?MVCTest?Rest?GET
6)修改后的UserController代碼
package?cn.kolbe.spring.mvc.controller;
import?org.springframework.stereotype.Controller;
import?org.springframework.web.bind.annotation.PathVariable;
import?org.springframework.web.bind.annotation.RequestMapping;
import?org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping(path?=?"/user")
public?class?UserController?{
@RequestMapping(value="/{id}",?method=RequestMethod.GET)
public?String?show(@PathVariable("id")?Integer?id)?{
System.out.println("查看id為:"?+?id?+?"的user");
return?"success";
}
@RequestMapping(value="/{id}",?method=RequestMethod.PUT)
public?String?update(@PathVariable("id")?Integer?id)?{
System.out.println("更新id為:"?+?id?+?"的user");
return?"success";
}
@RequestMapping(value="/{id}",?method=RequestMethod.DELETE)
public?String?destroy(@PathVariable("id")?Integer?id)?{
System.out.println("刪除id為:"?+?id?+?"的user");
return?"success";
}
@RequestMapping(value="",?method=RequestMethod.POST)
public?String?create()?{
System.out.println("新建user");
return?"success";
}
}
注:如果你的web項目是運行在Tomcat 8下,你會發現被過濾成DELETE和PUT請求,到達控制器后,返回時(forward)會報HTTP 405的錯誤提示
HTTP?Status?405?-?Request?method?'DELETE'?not?supported
或
HTTP?Status?405?-?JSPs?only?permit?GET?POST?or?HEAD
有三種解決方案:
(一)將 Tomcat 8 改為 Tomcat 7,在Tomcat 7 下運行是正常的
(二)將請求轉發(forward)改為請求重定向(redirect)
(三)自己手動寫一個Filter來包裝HttpRequest中的getMethod()方法
下面介紹一下第(三)種做法,也就是自己寫一個Filter來包裝從服務器發回來的HttpRequest請求:
大致說一下流程,
1. 在第1步中,客戶端發送請求至服務器,這時如果發送的是POST請求且帶有以_method為名的參數會被Spring的HiddenHttpMethodFilter給攔截。
2.?HiddenHttpMethodFilter內有一個靜態內部類通過繼承HttpServletRequestWrapper類并重寫getMethod()方法,將該方法返回值設為_method隱藏域的值。
3. HiddenHttpMethodFilter在包裝好Request后,將請求發往服務器的控制器中對應的方法處理器,這時的請求變成了圖中的 3、WrapperRequest by SpringFilter
4. 服務器處理完請求后,產生了一個forward請求,產生相應的請求處理信息發往客戶端,注意這時的request的getMethod()方法仍然是HiddenHttpMethodFilter包裝過的
5. 我們需要在服務器的響應請求到達客戶端前進行攔截,這也是最關鍵的一步,通過自定義過濾器MyHttpMethodFilter進一步包裝請求,將getMethod()方法返回值改成POST或GET即可
6. 在web.xml中配置該filter,注意dispatcher結點值必須為FORWARD。由于字數超限,暫時說到這。。。
myFilter
/*
FORWARD
總結
以上是生活随笔為你收集整理的requestmapping配置页面后_Spring MVC 入门指南(二):@RequestMapping用法详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【scikit-learn基础】--『监
- 下一篇: 原生H5+JS+CSS实现音乐播放器(上