URI Template Patterns
@RequestMapping
在springmvc中,URI templates 我们可以用 @RequestMapping 来作为我们的路径映射方法.
@RequestMapping有如下几种,而常见的就只有GET,POST,PUT(文件上传)
public enum RequestMethod {
GET,
HEAD,
POST,
PUT,
PATCH,
DELETE,
OPTIONS,
TRACE;
private RequestMethod() {
}
}
当我们需要做路径匹配时,我们只需要再方法体上添加@RequestMapping即可,如下:
@RequestMapping("/helloWorld")
public String helloWorld(Model model) {
model.addAttribute("message", "Hello World!");
return "helloWorld";
}
@RequestMapping允许我们通过正则表达式来匹配传值
@RequestMapping("/spring-web/{symbolicName:[a-z-]}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]}")
public void handle(@PathVariable String version, @PathVariable String extension) {
}
}
@RequestMapping可以通过params做相应的判断,看是否可以匹配,/bbs.do?method=getList 可以访问到方法getList() ;而访问/bbs.do/spList则会报错.
@RequestMapping("/bbs.do")
public class BbsController {
@RequestMapping(params = "method=getList")
public String getList() {
return "list";
}
@RequestMapping(value= "/spList")
public String getSpecialList() {
return "splist";
}
}
@PathVariable
在Spring MVC中,使用@PathVariable注解将方法的参数与URI模板的变量绑定在一起。
如下:
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
model.addAttribute("owner", owner);
return "displayOwner";
}
加入传进来的值和我们方法体里的值不一致,我们可以赋上一个变量名,如下:
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId") String theOwner, Model model) {
// implementation omitted
}
一个方法体可以写多个@PathVariable,如下
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId") String theOwner,@PathVariable("ownerId") String theOwner2, Model model) {
// implementation omitted
}
Matrix Variables
springmvc 允许我们匹配Matrix URIs路径,前提是要在配置文件中添加如下注释
<mvc:annotation-driven enable-matrix-variables="true"/>
@MatrixVariable的用法,输入路径// GET /pets/42;q=11;r=22
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET)
public void findPet(@PathVariable String petId, @MatrixVariable int q) {
// petId == 42
// q == 11
}
如果路径传了两个同样的变量名,则可以这样匹配
// GET /owners/42;q=11/pets/21;q=22
@RequestMapping(value = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET)
public void findPet(
@MatrixVariable(value="q", pathVar="ownerId") int q1,
@MatrixVariable(value="q", pathVar="petId") int q2) {
// q1 == 11
// q2 == 22
}
设置默认值
// GET /pets/42
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET)
public void findPet(@MatrixVariable(required=false, defaultValue="1") int q) {
// q == 1
}
冷门知识点
Path Pattern
除了URI Template,@RequestMapping注解还支持Ant风格的路径模式(如: /myPath/.do)。或组合使用URI Template和Path Pattern(如:/owners//pets/{petId})。
URL匹配优先级
当URL匹配多个pattern时,需要排序找到特定的匹配。
占位符Placeholders
注解@RequestMapping支持${…}占位符。