20161214

来源:互联网 发布:mac如何卸载office 编辑:程序博客网 时间:2024/06/10 04:58

springmvc注解

需要通过处理器映射DefaultAnnotationHandlerMapping 和处理器适配器 AnnotationMethodHandlerAdapter 来开启支持@Controller 和 @RequestMapping 注解的处理器。

重点内容
@Controller: 用于标识是处理器类;
@RequestMapping: 请求到处理器功能方法的映射规则;
@RequestParam: 请求参数到处理器功能处理方法的方法参数上的绑定;
@ModelAttribute: 请求参数到命令对象的绑定;
@SessionAttributes : 用于声 明 session 级别 存 储 的 属性, 放置 在处 理器 类上,通常列出模型 属性(如@ModelAttribute) 对应的名称,则这些属性会透明的保存到 session 中;
@InitBinder: 自 定义数据绑定注册支持, 用于将请求参数转换到命令对象属性的对应类型;
@CookieValue: cookie 数据到处理器功能处理方法的方法参数上的绑定;
@RequestHeader: 请求头( header) 数据到处理器功能处理方法的方法参数上的绑定;
@RequestBody: 请求的 body 体的绑定(通过 HttpMessageConverter 进行类型转换);
@ResponseBody: 处理器功能处理方法的返回值作为响应体(通过 HttpMessageConverter 进行类型转换);
@ResponseStatus: 定义处理器功能处理方法/异常处理器返回的状态码和原因;
@ExceptionHandler: 注解式声明异常处理器;
@PathVariable: 请求 URI 中的模板变量部分到处理器功能处理方法的方法参数上的绑定, 从而支持 RESTful 架构风
格的 URI;


@RequestMapping
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
RequestMapping注解有六个属性,下面我们把她分成三类进行说明。

  1. value, method;

    value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明); method:
    指定请求的method类型, GET、POST、PUT、DELETE等;

  2. consumes,produces;
    指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
@Controller@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")public void addPet(@RequestBody Pet pet, Model model) {        // implementation omitted}
方法仅处理request Content-Type为“application/json”类型的请求 produces:   指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
@Controller@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")@ResponseBodypublic Pet getPet(@PathVariable String petId, Model model) {        // implementation omitted}

方法仅处理request请求中Accept头中包含了”application/json”的请求,同时暗示了返回的内容类型为application/json
3. params,headers;
params:
指定request中必须包含某些参数值是,才让该方法处理。
headers:
指定request中必须包含某些指定的header值,才能让该方法处理请求。

 @Controller@RequestMapping("/owners/{ownerId}")public class RelativePathUriTemplateController {  @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {        // implementation omitted  }}

仅处理请求中包含了名为“myParam”,值为“myValue”的请求;

headers的样例:@Controller@RequestMapping("/owners/{ownerId}")public class RelativePathUriTemplateController {@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {        // implementation omitted  }}

仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.ifeng.com/”的请求;

@ModelAttribute:
被@ModelAttribute注释的方法会在此controller每个方法执行前被执行,因此对于一个controller映射多个URL的用法来说,要谨慎使用。

0 0
原创粉丝点击