[Spring MVC]学习笔记--@RequestMapping

@RequestMapping是用来将请求的url,映射到整个类,或者里面的方法。

@Controller
@RequestMapping("/test")
public class TestController {
    private final TestService service;

    @Autowired
    public TestController(TestService testService) {
        this.service = testService;    
    }

    @RequestMapping(method = RequestMethod.GET)
    public Map<String, Test> get() {
        return service.getTests();
    }

    @RequestMapping(value="/new", method=RequestMethod.GET)
    public Test getNewTest() {
        return new Test();
    }
}

 

在URL中包含变量

@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";
}

在URL的中使用变量名ownerId,当该方法处理请求时,会把url中ownerId的值传给ownerId。

如果变量名不一致的话,可以使用下面的方法。

@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId") String theOwner, Model model) {
...
}

注意1:变量可以包含多个。

注意2:当用于Map<String,String>时,map用来存放所有的变量。

 

Matrix Variables使用

格式:/cars;color=red,green,blue;year=2014  变量之间用";", 值之间用",".

要使用Matrix Variables,首先要修改xml文件

<mvc:annotation-driven enable-matrix-variables="true"/>

 

多个参数例子

// GET /owners/2;q=1/pets/3;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 == 1
    //q2 == 22
}

 

默认值

//Get /pets/42
@RequestMapping(value="/pets/{petId}",method=RequestMethod.GET)
public void findPet(@MatrixVariable(required=false, defaultValue="1") int q) {
     // q == 1   
}

 

获得所有matrix variables值

// GET /owners/42;q=11;r=12/pets/21;q=22;s=23
@RequestMapping(value = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET)
public void findPet(
        @MatrixVariable Map<String,String> matrixVars,
        @MatrixVariable(pathVar="petId" Map<String,String> petMatrixVars) {
    //matrixVars: ["q":[11,22], "r":12, "s":23]
    //petMatrixVars: ["q": 11, "s" : 23]
}

 

指定条件

consumes: 只有当请求的Content-Type值为指定的值时,才进行处理。

@RequestMapping(..., consumes="application/json")

produces:只有当请求中的Accept值匹配指定的值时,才进行处理。

@RequestMapping(..., produces="application/json")

params:根据请求中的parameters来过滤

@RequestMapping(..., params="myParam=myValue")

注:表达式可以为"myParam", "!myParam", "myParam=myValue";分别表示存在,不存在,为特定值。

headers: 根据请求中的headers来过滤。(用法同params)

@RequestMapping(..., headers="myHeader=myValue")

注:如果是针对content-type的话,建议用consumes和produces。

 

@RequestParam

@RequestParam可以把request中的parameter绑定到method parameter。

例如xxx/pet?petId=4

@RequestMapping(value = "/pet")
public String test(@RequestParam("petId") int petId, ModelMap model) {
    ...
}

被标注了@RequestParam后,默认是必须的,可以增加required=false来标记,同时最好增加一个defaultValue的值。

posted @ 2014-08-11 15:40  lemon_bar  阅读(2160)  评论(0编辑  收藏  举报