- @RequestMapping
這個是最常用的注解,可以配置在類上,也可以配置在方法上,兩個一起作用組成方法能夠響應的請求路徑,舉例如下

1 package org.zln.myWeb.controller; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.*; 6 import org.zln.myWeb.domain.T00_User; 7 import org.zln.myWeb.service.T00_UserService; 8 9 import java.util.HashMap; 10 import java.util.Map; 11 12 /** 13 * Created by sherry on 16/8/6. 14 */ 15 @Controller 16 @RequestMapping("/myWeb") 17 public class T00_UserController { 18 19 @Autowired 20 private T00_UserService t00_userService; 21 22 @RequestMapping("/name.json") 23 public @ResponseBody Map<String,String> showName(@RequestParam("id") Integer id){ 24 T00_User t00_user = t00_userService.getT00_UserById(id); 25 Map<String,String> map = new HashMap<>(); 26 map.put("name",t00_user.getName()); 27 return map; 28 } 29 }
showName方法能夠處理的就是請求路徑為 /myWeb/name.json 的請求
可以配置多個路徑
@RequestMapping(value={"/myWeb","/"})
URI模板映射
@RequestMapping("/myWeb/user/{userId}")
其中{xxx}是占位符,在方法參數中,通過@PathVariable能夠提取URI中的userId值
當然,占位符可以使用多個
Ant風格的URL路徑
@RequestMapping("/myWeb/**")
所有 /myWeb/開頭的地址都能夠映射到,但是,當產生沖突的時候,參考最長匹配優先原則
@RequestMapping("/myWeb/name?")
一個問號 ?,匹配任意一個字符
一個星號 *,匹配任意多個字符
Ant風格和URI模板是可以混用的
正則表達式
@RequestMapping("/myWeb/{正則表達式名:表達式}")
方法參數中,使用@PathVariable("正則表達式名") 獲取到請求地址值
- 請求方法限定
@RequestMapping(value = "/name.json",method = {RequestMethod.GET})
也可以配置允許多種提交方式
@RequestMapping(value = "/name.json",method = {RequestMethod.GET,RequestMethod.POST})
一般瀏覽器只支持GET、POST兩種請求方法,Spring MVC默認開啟了對GET、POST、DELETE、PUT、HEAD的支持
對於OPTIONS、TRACE請求方法的支持,需要在web.xml中配置
- 請求參數限定
請求參數中必須有某種參數,也可以設置參數的值必須為某個指定值,才映射到方法
@RequestMapping(value = "/name.json",method = {RequestMethod.GET,RequestMethod.POST,},params = "id")
@RequestMapping(value = "/name.json",method = {RequestMethod.GET,RequestMethod.POST,},params = "!id")
!id表示沒有id請求參數
@RequestMapping(value = "/name.json",method = {RequestMethod.GET,RequestMethod.POST,},params = "id=1")
指定id值
@RequestMapping(value = "/name.json",method = {RequestMethod.GET,RequestMethod.POST,},params = "submit!=create")
指定值不等於某個值
@RequestMapping(value = "/name.json",method = {RequestMethod.GET,RequestMethod.POST,},params = {"test1","test2=1"})
也可以配置多個參數值,多個參數之間的配置是且的關系
- 請求頭信息限定
@RequestMapping(value = "/name.json",method = {RequestMethod.GET,RequestMethod.POST,},params = "id",headers = "Accept")
headers用來配置請求頭信息,如上表示請求頭信息必須有Accept參數
headers="!Accept",請求頭不允許包含Accept參數
同時,和params一樣,也可以配置多個請求頭參數
通過以上的方式,基本是已經可以完全滿足日常使用了