zoukankan      html  css  js  c++  java
  • 深入SpringMVC注解

    原文链接:https://blog.csdn.net/chenpeng19910926/article/details/70837756

    @Controller

    在SpringMVC 中提供了一个非常简便的定义Controller 的方法,你无需继承特定的类或实现特定的接口,只需使用@Controller 标记一个类是Controller ,然后使用@RequestMapping 和@RequestParam 等一些注解用以定义URL 请求和Controller 方法之间的映射,这样的Controller 就能被外界访问到。此外Controller 不会直接依赖于HttpServletRequest 和HttpServletResponse 等HttpServlet 对象,它们可以通过Controller 的方法参数灵活的获取到。

    单单使用@Controller 标记在一个类上还不能真正意义上的说它就是SpringMVC 的一个控制器类,因为这个时候Spring 还不认识它。那么要如何做Spring 才能认识它呢?这个时候就需要我们把这个控制器类交给Spring 来管理。有两种方式:

      (1)在SpringMVC 的配置文件中定义MyController 的bean 对象。

      (2)在SpringMVC 的配置文件中告诉Spring 该到哪里去找标记为@Controller 的Controller 控制器。

    <!--方式一-->  
    <bean class="com.host.app.web.controller.MyController"/>  
    <!--方式二-->  
    < context:component-scan base-package = "com.host.app.web" />//路径写到controller的上一层(扫描包详解见下面浅析)  

    component-scan 默认扫描的注解类型是 @Component,不过,在 @Component 语义基础上细化后的 @Repository, @Service 和 @Controller 也同样可以获得 component-scan 的青睐

    有了<context:component-scan>,另一个<context:annotation-config/>标签根本可以移除掉,因为已经被包含进去了

    另外<context:annotation-config/>还提供了两个子标签

    1.        <context:include-filter> //指定扫描的路径

    2.       <context:exclude-filter> //排除扫描的路径

    <context:component-scan>有一个use-default-filters属性,属性默认为true,表示会扫描指定包下的全部的标有@Component的类,并注册成bean.也就是@Component的子注解@Service,@Reposity等。

    这种扫描的粒度有点太大,如果你只想扫描指定包下面的Controller或其他内容则设置use-default-filters属性为false,表示不再按照scan指定的包扫描,而是按照<context:include-filter>指定的包扫描,示例:

    <context:component-scan base-package="com.tan" use-default-filters="false">  
            <context:include-filter type="regex" expression="com.tan.*"/>//注意后面要写.*  
    </context:component-scan>  
    当没有设置use-default-filters属性或者属性为true时,表示基于base-packge包下指定扫描的具体路径
    <context:component-scan base-package="com.tan" >  
            <context:include-filter type="regex" expression=".controller.*"/>  
            <context:include-filter type="regex" expression=".service.*"/>  
            <context:include-filter type="regex" expression=".dao.*"/>  
    </context:component-scan>  
    无论哪种情况<context:include-filter>和<context:exclude-filter>都不能同时存在

    @Component

    相当于通用的注解,当不知道一些类归到哪个层时使用,但是不建议

    @Repository

    用于注解dao层,在daoImpl类上面注解。

    @RequestMapping(这个有些属性是我没有注意到的)

    RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

    RequestMapping注解有六个属性,下面我们把她分成三类进行说明(下面有相应示例)。

    1、 value, method;

    value:     指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);@RequestMapping 中还支持通配符“* ”。如下面的代码我就可以使用/myTest/whatever/wildcard.do 访问到Controller 的testWildcard 方法。如:

    @Controller  
    @RequestMapping ( "/myTest" )  
    public class MyController {  
        @RequestMapping ( "*/wildcard" )  
        public String testWildcard() {  
           System. out .println( "wildcard------------" );  
           return "wildcard" ;  
        }    
    }  

    method:  指定请求的method类型, GET、POST、PUT、DELETE等;

    @RequestMapping (value= "testMethod" , method={RequestMethod. GET , RequestMethod. DELETE })  
        public String testMethod() {  
           return "method" ;  
        }  

    2、consumes,produces

    consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

    produces:    指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

    3、params,headers

    params: 指定request中必须包含某些参数值是,才让该方法处理。

    @RequestMapping (value= "testParams" , params={ "param1=value1" , "param2" , "!param3" })  
        public String testParams() {  
           System. out .println( "test Params..........." );  
           return "testParams" ;  
        }  

    用@RequestMapping 的params 属性指定了三个参数,这些参数都是针对请求参数而言的,它们分别表示参数param1 的值必须等于value1 ,参数param2 必须存在,值无所谓,参数param3 必须不存在,只有当请求/testParams.do 并且满足指定的三个参数条件的时候才能访问到该方法。所以当请求/testParams.do?param1=value1&param2=value2 的时候能够正确访问到该testParams 方法,当请求/testParams.do?param1=value1&param2=value2&param3=value3 的时候就不能够正常的访问到该方法,因为在@RequestMapping 的params 参数里面指定了参数param3 是不能存在的。

    headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

    @RequestMapping (value= "testHeaders" , headers={ "host=localhost" , "Accept" })  
        public String testHeaders() {  
           return "headers" ;  
        }  

    headers 属性的用法和功能与params 属性相似。在上面的代码中当请求/testHeaders.do 的时候只有当请求头包含Accept 信息,且请求的host 为localhost 的时候才能正确的访问到testHeaders 方法。

    @Resource和@Autowired(这个我曾经在spring学习中提到过)

    @Resource和@Autowired都是做bean的注入时使用,其实@Resource并不是Spring的注解,它的包是javax.annotation.Resource,需要导入,但是Spring支持该注解的注入。两者都可以写在字段和setter方法上。两者如果都写在字段上,那么就不需要再写setter方法。

    (1)@Autowired

    @Autowired为Spring提供的注解,需要导入包org.springframework.beans.factory.annotation.Autowired;只按照byType注入。

    @Autowired注解是按照类型(byType)装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它的required属性为false。如果我们想使用按照名称(byName)来装配,可以结合@Qualifier注解一起使用。

    (2)@Resource

    @Resource默认按照ByName自动注入,由J2EE提供,需要导入包javax.annotation.Resource。@Resource有两个重要的属性:name和type,而Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不制定name也不制定type属性,这时将通过反射机制使用byName自动注入策略。

    注:最好是将@Resource放在setter方法上,因为这样更符合面向对象的思想,通过set、get去操作属性,而不是直接去操作属性。

    @Resource装配顺序:

    ①如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常。

    ②如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常。

    ③如果指定了type,则从上下文中找到类似匹配的唯一bean进行装配,找不到或是找到多个,都会抛出异常。

    ④如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配。

    @Resource的作用相当于@Autowired,只不过@Autowired按照byType自动注入。

    handler method 参数绑定常用的注解

    handler method 参数绑定常用的注解,我们根据他们处理的Request的不同内容部分分为四类:(主要讲解常用类型)

    A、处理requet uri 部分(这里指uri template中variable,不含queryString部分)的注解:   @PathVariable;

    B、处理request header部分的注解:   @RequestHeader, @CookieValue;

    C、处理request body部分的注解:@RequestParam,  @RequestBody;

    D、处理attribute类型是注解: @SessionAttributes, @ModelAttribute;

    @ModelAttribute(项目中没有使用过)

    代表的是:该Controller的所有方法在调用前,先执行此@ModelAttribute方法,可用于注解和方法参数中,可以把这个@ModelAttribute特性,应用在BaseController当中,所有的Controller继承BaseController,即可实现在调用Controller时,先执行@ModelAttribute方法。 @ModelAttribute 主要有两种使用方式,一种是标注在方法上,一种是标注在 Controller 方法参数上。

    当 @ModelAttribute 标记在方法上的时候,该方法将在处理器方法执行之前执行,然后把返回的对象存放在 session 或模型属性中,属性名称可以使用 @ModelAttribute(“attributeName”) 在标记方法的时候指定,若未指定,则使用返回类型的类名称(首字母小写)作为属性名称。关于 @ModelAttribute 标记在方法上时对应的属性是存放在 session 中还是存放在模型中,我们来做一个实验,看下面一段代码。

    @Controller  
    @RequestMapping ( "/myTest" )  
    public class MyController {  
      
        @ModelAttribute ( "hello" )  
        public String getModel() {  
           System. out .println( "-------------Hello---------" );  
           return "world" ;  
        }  
      
        @ModelAttribute ( "intValue" )  
        public int getInteger() {  
           System. out .println( "-------------intValue---------------" );  
           return 10;  
        }  
      
        @RequestMapping ( "sayHello" )  
        public void sayHello( @ModelAttribute ( "hello" ) String hello, @ModelAttribute ( "intValue" ) int num, @ModelAttribute ( "user2" ) User user, Writer writer, HttpSession session) throws IOException {  
           writer.write( "Hello " + hello + " , Hello " + user.getUsername() + num);  
           writer.write( "
    " );  
           Enumeration enume = session.getAttributeNames();  
           while (enume.hasMoreElements())  
               writer.write(enume.nextElement() + "
    " );  
        }  
      
        @ModelAttribute ( "user2" )  
        public User getUser(){  
           System. out .println( "---------getUser-------------" );  
           return new User(3, "user2" );  
        }  
    }  

    当我们请求 /myTest/sayHello.do 的时候使用 @ModelAttribute 标记的方法会先执行,然后把它们返回的对象存放到模型中。最终访问到 sayHello 方法的时候,使用 @ModelAttribute 标记的方法参数都能被正确的注入值。执行结果如下所示:

     Hello world,Hello user210

        由执行结果我们可以看出来,此时 session 中没有包含任何属性,也就是说上面的那些对象都是存放在模型属性中,而不是存放在 session 属性中。那要如何才能存放在 session 属性中呢?这个时候我们先引入一个新的概念 @SessionAttributes ,它的用法会在讲完 @ModelAttribute 之后介绍,这里我们就先拿来用一下。我们在 MyController 类上加上 @SessionAttributes 属性标记哪些是需要存放到 session 中的。

     @SessionAttributes(有过需求但是最终使用的是HTTPSession)

     @SessionAttributes即将值放到session作用域中,写在class上面。看下面的代码:

    @Controller  
    @RequestMapping ( "/myTest" )  
    @SessionAttributes (value={ "intValue" , "stringValue" }, types={User. class })  
    public class MyController {  
      
        @ModelAttribute ( "hello" )  
        public String getModel() {  
           System. out .println( "-------------Hello---------" );  
           return "world" ;  
        }  
      
        @ModelAttribute ( "intValue" )  
        public int getInteger() {  
           System. out .println( "-------------intValue---------------" );  
           return 10;  
        }  
         
        @RequestMapping ( "sayHello" )  
        public void sayHello(Map<String, Object> map, @ModelAttribute ( "hello" ) String hello, @ModelAttribute ( "intValue" ) int num, @ModelAttribute ( "user2" ) User user, Writer writer, HttpServletRequest request) throws IOException {  
           map.put( "stringValue" , "String" );  
           writer.write( "Hello " + hello + " , Hello " + user.getUsername() + num);  
           writer.write( "
    " );  
           HttpSession session = request.getSession();  
           Enumeration enume = session.getAttributeNames();  
           while (enume.hasMoreElements())  
               writer.write(enume.nextElement() + "
    " );  
           System. out .println(session);  
        }  
      
        @ModelAttribute ( "user2" )  
        public User getUser() {  
           System. out .println( "---------getUser-------------" );  
           return new User(3, "user2" );  
        }  
    }  

    首先查询 @SessionAttributes有无绑定的hello对象,若没有则查询@ModelAttribute方法层面上是否绑定了hello对象,若没有则将URI template中的值按对应的名称绑定到hello对象的各属性上。

    在上面代码中我们指定了属性为 intValue 或 stringValue 或者类型为 User 的都会放到 Session中,利用上面的代码当我们访问 /myTest/sayHello.do 的时候,结果如下:

     Hello world,Hello user210

    仍然没有打印出任何 session 属性,这是怎么回事呢?怎么定义了把模型中属性名为 intValue 的对象和类型为 User 的对象存到 session 中,而实际上没有加进去呢?难道我们错啦?我们当然没有错,只是在第一次访问 /myTest/sayHello.do 的时候 @SessionAttributes 定义了需要存放到 session 中的属性,而且这个模型中也有对应的属性,但是这个时候还没有加到 session 中,所以 session 中不会有任何属性,等处理器方法执行完成后 Spring 才会把模型中对应的属性添加到 session 中。所以当请求第二次的时候就会出现如下结果:

     Hello world,Hello user210

    user2

    intValue

    stringValue

    当 @ModelAttribute 标记在处理器方法参数上的时候,表示该参数的值将从模型或者 Session 中取对应名称的属性值,该名称可以通过 @ModelAttribute(“attributeName”) 来指定,若未指定,则使用参数类型的类名称(首字母小写)作为属性名称。

    @PathVariable(REST风格的体现,正则没有使用过)

    用于将请求URL中的模板变量映射到功能处理方法的参数上,即取出uri模板中的变量作为参数。如:

    @Controller    
    public class TestController {    
         @RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)    
         public String getLogin(@PathVariable("userId") String userId,    
             @PathVariable("roleId") String roleId){    
             System.out.println("User Id : " + userId);    
             System.out.println("Role Id : " + roleId);    
             return "hello";    
         }    
         @RequestMapping(value="/javabeat/{regexp1:[a-z-]+}",    
               method = RequestMethod.GET)    
         public String getRegExp(@PathVariable("regexp1") String regexp1){    
               System.out.println("URI Part 1 : " + regexp1);    
               return "hello";    
         }    
    }  
      
    @Controller  
    @RequestMapping ( "/test/{variable1}" )  
    public class MyController {  
      
        @RequestMapping ( "/showView/{variable2}" )  
        public ModelAndView showView( @PathVariable String variable1, @PathVariable ( "variable2" ) int variable2) {  
           ModelAndView modelAndView = new ModelAndView();  
           modelAndView.setViewName( "viewName" );  
           modelAndView.addObject( " 需要放到 model 中的属性名称 " , " 对应的属性值,它是一个对象 " );  
           return modelAndView;  
        }  
    }  

    @RequestHeader

    @RequestHeader 注解,可以把Request请求header部分的值绑定到方法的参数上。

    Host                    localhost:8080    
    Accept                  text/html,application/xhtml+xml,application/xml;q=0.9    
    Accept-Language         fr,en-gb;q=0.7,en;q=0.3    
    Accept-Encoding         gzip,deflate    
    Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7    
    Keep-Alive              300    
      
    @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

    @CookieValue 可以把Request header中关于cookie的值绑定到方法的参数上。

    例如有如下Cookie值:

      JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84

    @RequestMapping("/displayHeaderInfo.do")    
    public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie)  {    
    }   

    @RequestParam

    @RequestParam主要用于在SpringMVC后台控制层获取参数,类似一种是request.getParameter("name"),

    它有三个常用参数:defaultValue = "0", required = false, value = "isApp";

    defaultValue 表示设置默认值,

    required 铜过boolean设置是否是必须要传入的参数,

    value 值表示接受的传入的参数类型。

    @RequestBody

    该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;

    它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。

    因为配置有FormHttpMessageConverter,所以也可以用来处理 application/x-www-form-urlencoded的内容,处理完的结果放在一个MultiValueMap<String, String>里,这种情况在某些特殊需求下使用,详情查看FormHttpMessageConverter api;

    示例代码:

    @RequestMapping(value = "/something", method = RequestMethod.PUT)    
    public void handle(@RequestBody String body, Writer writer) throws IOException {    
      writer.write(body);    
    }   

    @ResponseBody

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

    使用时机:返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

    @ExceptionHandler

      注解到方法上,出现异常时会执行该方法

    @ControllerAdvice

      使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常

    @ControllerAdvice  
    public class GlobalExceptionHandler {  
      
        private final Logger logger = LoggerFactory.getLogger(getClass());  
      
        @ExceptionHandler(BusinessException.class)  
        public @ResponseBody ResponseMsg businessError(BusinessException exception) {  
            logger.info("Request raised a BusinessException, business code is {}", exception.getCode());  
            return new ResponseMsg(exception.getCode(), exception.getMessage());  
        }  
      
        @ExceptionHandler(Exception.class)  
        public @ResponseBody ResponseMsg sysError(Exception exception) {  
            String msg = "出错了";  
            if(exception instanceof MaxUploadSizeExceededException){  
                msg = "上传文件过大";  
            }  
            //exception.printStackTrace();  
            logger.error("Request raised " + exception.getClass().getSimpleName(), exception);  
            return new ResponseMsg(GeneralConst.SYS_ERROR, msg);  
        }  
      
    }  

    @InitBinder

    使用InitBinder来处理Date类型的参数

    //the parameter was converted in initBinder  
    @RequestMapping("/date")  
    public String date(Date date){  
        System.out.println(date);  
        return "hello";  
    }  
          
    //At the time of initialization,convert the type "String" to type "date"  
    @InitBinder  
    public void initBinder(ServletRequestDataBinder binder){  
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),  
                true));  
    }  
  • 相关阅读:
    文字编码转换器 V1.0 免费绿色版
    一把刀系统维护工具箱 v1.6 绿色版
    一把刀终极配置Win7/8版 v2.0 绿色版
    移动端 iframe的使用
    scale配合过渡的时候bug
    js 简体中文拼音对应表
    原生js快速渲染dom节点
    让我们的svg起飞,兼容ie9的神器
    盒模型
    Normalize.css 与 reset.css
  • 原文地址:https://www.cnblogs.com/wangxiayun/p/9147442.html
Copyright © 2011-2022 走看看