SpringMVC 注解

来源:互联网 发布:安卓源码编译环境搭建 编辑:程序博客网 时间:2024/05/06 05:52

@Controller

在 springmvc 2.5 之前通过继承 Controller 接口实现控制器

//接口定义public interface Controller {   ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception;}//实现方式public Mycontroller implements Controller{    ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception{        //do Something...    }}

在 springmvc 2.5 之后利用注解的方式(即 @Controller)实现控制器,实现了彻底解耦。一个类在使用了该注解之后就表明自己是一个控制器。

首先来看 @controller 的注解定义

// 表示作用类或接口上,在运行时有效Target({ElementType.TYPE})  Retention(RetentionPolicy.RUNTIME)Documented@Componentpublic @interface Controller {    String value() default "";}

实现方式

@Controllerpublic Mycontroller{}

@RequestMapping

@RequestMapping 表示用来处理请求地址映射,通过它 springmvc 可以实现对请求地址的精确匹配。

首先来看该注解的定义。

@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME) @Documented@Mappingpublic @interface RequestMapping {    //相关属性(用法在下面会详细介绍)    String[] value() default {};    RequestMethod[] method() default {};    String[] params() default {};    String[] headers() default {};    String[] consumes() default {};    String[] produces() default {};}

1.作用域

  • 单独在类上使用则不起效果

  • 在方法上单独使用,表示匹配 test/user 的请求路径

@Controllerpublic Mycontroller{    @RequestMapping(value="/user")    public ModelAndView handleRequest(ModelAndView ModelAndView){        // do Something...    }}
  • 在类,方法上混合使用,如果在类添加了@RequestMapping 注释后,那么方法上的 @RequestMapping 被认为是对类映射的窄化。表示匹配 test/annotation/user 的请求路径。
@Controller@RequestMapping(value="/annotation")public Mycontroller{    @RequestMapping(value="/user")    public ModelAndView handleRequest(ModelAndView ModelAndView){        // do Something...    }}

2.属性 - value

该属性用来指定具体的匹配路径,它具有以下几个特点:

  • value 的参数的开头是否 “/” 是一样的,但是为了规范,最好使用前者
//两者效果一样@RequestMapping(value="/user/login") @RequestMapping(value="user/login")
  • 结尾则不允许出现”/”。
//错误写法@RequestMapping(value="user/login/")
  • 遵循最长匹配原则,②③同时存在时,先匹配③。
//①可以匹配:/user/a, user/b@RequestMapping(value="/user/*")//②可以匹配:/user/a,user/a/bb @RequestMapping(value="/user/**")//③可以匹配:/user/a,user/b@RequestMapping(value="/user/{type}")//④可以匹配:/user/aa,/user/ab ,但不匹配: /user/a@RequestMapping(value="/user/a?")

3.属性 - RequestMethod

该属性用来匹配请求类型,我们首先来看看它的定义。

public enum RequestMethod {    //匹配的请求类型如下     GET,    HEAD,    POST,    PUT,    PATCH,    DELETE,    OPTIONS,    TRACE;    private RequestMethod() {    }}

以下是各个请求类型的具体作用,为了方便查阅,特在这里贴出。

方法 描述 GET 请求指定的页面信息,并返回实体主体。 HEAD 类似于get请求,只不过返回的响应中没有具体的内容,用于获取报头 POST 向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。POST请求可能会导致新的资源的建立和/或已有资源的修改。 PUT 从客户端向服务器传送的数据取代指定的文档的内容。 PATCH 实体中包含一个表,表中说明与该URI所表示的原内容的区别。 DELETE 请求服务器删除指定的页面。 OPTIONS 允许客户端查看服务器的性能。 TRACE 回显服务器收到的请求,主要用于测试或诊断。

关于 RequestMethod 的使用情况有两种:

  • RequestMethod 可单独使用,表示匹配任何路径下的指定请求。
//表示匹配 GET 请求,如果不匹配则返回 405 Method Not Allowed@RequestMapping(method=RequestMethod.GET)   //表示 GET 或 POST 类型的请求 @RequestMapping(method={RequestMethod.GET,RequestMethod.POST})  
  • 与参数 value 混合使用,表示“”关系,即两者都要满足。
@RequestMapping(value="/user" ,method=RequestMethod.GET)

4.属性 - param

param 表示请求参数,用来匹配请求中的请求参数(Query String Paramers),请求参数不匹配时返回 404 状态码。

//可以匹配:/user?username=test,/user?username=test2 @RequestMapping(params="username",value="/user" )//只能匹配:/user?username=test@RequestMapping(params="username = test")//不匹配:/user?username=test,其他均匹配@RequestMapping(params="username != test") //只能匹配:/user?username=test2&password=admin @RequestMapping(params={"username != test","password = admin") 

5.属性 - header

header 主要用来匹配请求头(RequestHeader)的参数,关于请求的具体参数可以参见(http://tools.jb51.net/table/http_header)。当请求头不匹配时,返回 406 状态码。

  • 可单独使用,表示匹配任何路径下的指定请求头
@RequestMapping(headers="Accept=text/html")
  • 与其他参数混合使用,表示“”关系
@RequestMapping(value="/user" ,method=RequestMethod.GET,headers="Accept=text/html")

6.属性 - consumes

consumes 用来匹配请求头的 content-type 属性。如果不匹配返回 416 状态码,表示客户端请求的范围无效。

  • content-type 属性表示请求的与实体对应的MIME信息,需手动指定,默认为空。
// 二者作用相同,只匹配请求头中 Content-Type 值为 text/html 的请求@RequestMapping(consumes="text/html") @RequestMapping(headers="Content-Type=text/html") 

7.属性 - produces

produces 用来匹配请求头中 Accept 属性。如果不匹配返回 406 错误码。

  • Accept 属性表示指定客户端能够接收的内容类型,即在该请求后的处理方法将产生对应的数据,而客户端必须能用接收。
//当请求头的 Accept 的值含有 text/html 则匹配并返回 text/html 类型的数据给客户端。@RequestMapping(produces="text/html")
  • 当在类和方法中同时指定该属性时,方法级别的将覆盖类级别的映射。
//请求头“Accept:application/xml”是成功的,而“text/html”将报406错误码//类定义@RequestMapping(value="/narrow", produces="text/html")  //方法定义@RequestMapping(produces="application/xml") 

Accept 属性遵循最明确的优先匹配

属性值 匹配顺序 Accept:text/html,application/xml,application/json ①text/html ②application/xml ③application/json Accept:application/xml;q=0.5,application/json;q=0.9,text/html ①text/html ②application/json ③application/xml(q参数为媒体类型的质量因子,越大则优先权越高(从0到1) Accept:/,text/*,text/html ①text/html ②text/* ③/

@CookieValue

该注解表示一个方法参数绑定到一个 HTTP cookie。支持 Servlet 和 Portlet 环境。

首先来看它的注解定义。

// 只能作用在参数上,只在运行时有效@Target({ElementType.PARAMETER})    @Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface CookieValue {    String value() default "";    boolean required() default true;    String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";}

1.属性 - value

value 参数,用来选择绑定指定的 cookie 。它可以绑定的对象类型有 String ,int,Cookie。

注意:绑定 String 时,直接获取 Cookie 的值。

public ModelAndView handleRequest(@CookieValue(value="JSESSIONID")Cookie sessionID){    //绑定 key = "JSESSIONID" 的 cookie    system.out.print("cookie 的值为:"+sessionID.getValue());}public ModelAndView handleRequest(@CookieValue(value="JSESSIONID")String sessionIDValue){    //绑定 key = "JSESSIONID" 的 cookie 的值    system.out.print("cookie 的值为:"+sessionIDValue;}

2.属性 - required

required 默认为 true,不匹配时返回 400 状态码。

//当请求头不包含 key = "JSESSIONID" 的 cookie 时,返回 400public ModelAndView handleRequest(@CookieValue(value="JSESSIONID2")Cookie sessionIDValue)//当请求头不包含 key = "JSESSIONID" 的 cookie 时,返回 400public ModelAndView handleRequest(@CookieValue(value="JSESSIONID2",required=true)String sessionIDValue)//当请求头不包含 key = "JSESSIONID" 的 cookie 时,程序正常运行public ModelAndView handleRequest(@CookieValue(value="JSESSIONID2",required=false)Cookie sessionIDValue)

3.属性 - defaultValue

defaultValue 默认为空,当 defaultValue 存在值时,required 则不生效。表示当绑定参数的值为空时,则取 defaultValue 的值。

// 程序则正常运行,且 sessionID的值为123456public ModelAndView handleRequest(@CookieValue(value="JSESSIONID2",defaultValue="123456")String sessionID),// 会抛出转换失败的异常public ModelAndView handleRequest(@CookieValue(value="JSESSIONID2",defaultValue="123456")Cookie sessionID),

@RequestHeader

该注解可以把 Request 请求 header 部分的值绑定到方法的参数上。关于请求头的部分内容下图所示:

Alt text

首先来看它的注解定义:

@Target(ElementType.PARAMETER)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface RequestHeader {    String value() default "";    boolean required() default true;    String defaultValue() default ValueConstants.DEFAULT_NONE;}

该注解的属性与 @CookieValue 的属性无异,这里不再讲解,只简单说下该注解的使用方法。

public ModelAndView handleRequest(@RequestHeader(value="Accept")String accept){    system.out.print("Accept为:"+accept);}

@RequestParam

该注解可以作用请求参数的数据绑定。

首先来看它的注解定义。

public @interface RequestParam {    String value() default "";    boolean required() default true;    String defaultValue() default ValueConstants.DEFAULT_NONE;}

因为在服务端可以使用 request.getParameter() 方式获取参数,所以可以处理 get 方式中queryString的值,也可以处理 post 方式中 body data的值。关于 get/post 方法的请求参数如下图所示:

  • GET 请求参数

Alt text

  • POST 请求参数

Alt text

凡是被绑定的请求参数如果是原子类型:必须有值,否则返回 400 错误状态码。如果想要允许空值请使用包装类代替。

例如 Boolean 包装类型类型:默认 Boolean.FALSE,其他引用类型默认为 null。

//对请求参数中的 name 进行绑定public ModelAndView handleRequest(@RequestParam(value="name")String username){    system.out.print("name为:"+username);}//当不使用注解时,只要方法的参数名称和请求参数名称一致,也可以自动绑定 public ModelAndView handleRequest(String name){    system.out.print("name为:"+name);}

@PathVariable

用来绑定 URI 模板变量值。

首先来看它的定义。

@Target({ElementType.PARAMETER})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface PathVariable {    String value() default "";}

发现它只有一个属性,下面简单说下该注解的使用方法。

@RequestMapping(value="/user/{type}")public ModelAndView handleRequest(@PathVariable String type){    system.out.print("type为:"+type);}

@ModelAttribute

用来绑定请求参数到命令对象。

首先来看它的定义。

@Target({ElementType.PARAMETER, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface ModelAttribute {    String value() default "";}
  • 绑定请求参数到命令对象,放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑定流程。
// 定义 Model 类public class UserModel {    private String username;        private String password;    //...省略 getter 和 setter}// 在控制器里定义处理方法@RequestMapping(value="/user")public ModelAndView handleRequest(@ModelAttribute(value="userModel")UserModel userModel){    // do Something...};// 在登录界面可以直接取值,页面的值与 value 的值需一致用户名:<input type="text" value="${userModel.username}">密   码:<input type="text" value="${userModel.password}">
  • 当 URI 模板变量和请求参数同名时,URI 模板变量具有高优先权。
// 请求路径为 /user/test?username=admin&password=123 ,最终页面 username 的值为 test@RequestMapping(value="/user/{username}")public ModelAndView handleRequest(@PathVariable String username,@ModelAttribute(value="userModel")UserModel userModel){    // do Soemething...};
  • 放在控制器的普通方法(非请求转发方法)上时,是为要展示的表单准备引用
    对象,如注册时需要选择的所在城市等,而且在执行请求转发(@RequestMapping 注解的方法)之前,自动添加到模型对象中,用于视图页面展示时使用。
//当该控制器包含以 @ModelAttribute 定义的方法,匹配路径时默认先进入该方法并将返回的参数的绑定对象@ModelAttribute(value="cityList")public List<String> cityList(){    return Arrays.asList("北京","上海");}

@RequestBody

作用:

  • 该注解用于读取 Request 请求的 body 部分数据,使用系统默认配置的HttpMessageConverter 进行解析,然后把相应的数据绑定到要返回的对象上。

  • 再把HttpMessageConverter 返回的对象数据绑定到 controller中方法的参数上。

首先来它的注解定义。

@Target(ElementType.PARAMETER)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface RequestBody {}

该注解用于匹配 Rquest Header(请求头)中 Content-Type 属性为 application/json, application/xml 的请求。

  • 使用 PostMan 发起请求:

Alt text

  • 在后台接收请求
//①首先定义一个 Model 类public clasS Person{    private String name;    private String age;    // ...省略 getter,setter}// ②控制器中匹配请求的方法@RequestMapping("/hello")public ModelAndView handleRequest(ModelAndView model,@RequestBody  Person person) {    System.out.println(person.getName());    // do something...

@ResponseBody

该注解用于将 Controller 的方法返回的对象,通过适当的 HttpMessageConverter 转换为指定格式后,写入到 Response 对象的 body 数据区。

注解定义:

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface ResponseBody {}

使用该注解后,返回的数据不是 html 标签的页面,而是其他某种格式的数据(如json、xml等,前提需要在 springmvc 的配置文件中配置适当的 HttpMessageConverter 转换器)

@ResponseBodypublic String handleRequest(String type){    type = "test";    return type;}
0 0