1.@PathVariable
使用@RequestMapping URI template样式映射时,url/{param},这时的param可通过@Pathvariable注解绑定它传过来的值到方法的参数上
@Controller
@RequestMapping("/owners/{ownerId}")
public class PathVariableUriController {
@RequestMapping("/pets/{petId}")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
mothodBody;
}
}
示例中,传入的owerId的值为1,petId为2时,URL为/owners/1/petId/2
2.@RequestHeader和@CookieValue
@RequestHeader注解,可以把Request请求header部分的值绑定到方法的参数上。
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding, @RequestHeader("Keep-Alive") long keepAlive) {
}
上面的代码,把request header部分的Accept-Encoding的值,绑定到参数encoding上了, Keep-Alive header的值绑定到参数keepAlive上。
@CookieValue可以把Request header中关于cookie的值绑定到方法的参数上。
3.@RequestParam, @RequestBody
@RequestParam:
A)用来处理Content-Type: 为application/x-www-form-urlencoded编码的内容,提交方式GET、POST;
B)该注解有两个属性:value、required;value用来指定要传入值的id名称,required用来指示参数是否必须绑定;
@RequestBody:
A)该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;
B)它是通过使用HandlerAdapter配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。
4.@ModelAttribute
用于方法上时:通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;
用于参数上时:用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:
A)@ModelAttribute 用于方法上时指定的model对象;
B)new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。
// Add one attribute
// The return value of the method is added to the model under the name "account"
// You can customize the name via @ModelAttribute("myAccount")
@ModelAttribute
public Account addAccount(@RequestParam String number) {
return accountManager.findAccount(number);
}
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute Pet pet) {
}
查询@ModelAttribute方法层面上是否绑定了Pet对象,若没有则将URItemplate中的值按对应的名称绑定到Pet对象的各属性上。