zoukankan      html  css  js  c++  java
  • SpringMVC---其它常用注解

    常用注解

    • PathVariable

      @RequestMapping注解中使用占位符的情况下,需要使用@PathVariable注解指定占位符参数。即指定占位符中的值与方法中哪一个参数进行匹配。如果方法中的参数名与url中{}里面(占位符)的名字一样,则可以省略@PathVariable(“userId”)中的userId,即@ PathVariable  String userId

    @RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET) 
    
    public String getLogin(@PathVariable("userId") String userId){ 
    
      System.out.println("User Id : " + userId); 
    
      return "hello"; 
    
    }
    • RequestParam

      在SpringMVC后台控制层获取参数的方式主要有两种,一种是request.getParameter(“name”),另外一种是用注解@RequestParam直接获取。@RequestParam有三个属性value(参数名)、required(是否必须有该参数值)、defaultValue(默认值)。在方法中使用,如果在方法中某参数使用了该注解,那么在请求中必须包含该参数,否则不会触发。在请求中即使没有方法中注解的参数也要触发该方法,则可以通过设置required属性为false即可,默认为true。如果参数是int/boolean数据类型的值,则不传递该参数会报错,因为int/boolean类型不能赋null值。所以建议使用Integer/Boolean

    public String getLogin(@RequestParam (value="userId", required=true,defaultValue=0) String userId, @RequestParam String userName){ 
    
      System.out.println("User Id : " + userId); 
    
      return "hello";
    
    }
    • CookieValue

      读取Cookies中的值,并且赋值给变量。有三个属性value、required、defaultValue,用法与RequestParam用法类似

    • SessionAttributes

      如果需要在多个请求之间共用某个数据,那么我们通常将数据保存在session中。如果希望在多个请求之间共用某个模型属性数据,则可以在控制器类标注一个@SessionAttributes,SpringMVC会将模型中对应的属性暂时保存到HttpSession中。除了使用SessionAttributes,还可以使用request.getSession()来处理session数据。

    • ResponseBody

    用于将Controller的方法返回的对象,通过适当的HttpMessageConverter(转换器)转换为指定格式后,写入到Response对象的body数据区,一般在返回值不是某页面时使用,如返回json、xml等时使用,使用ResponseBody将会跳过视图处理的部分。HttpMessageConverter接口负责将请求转换成一个对象,并将对象输出为响应信息,spring-mvc.xml配置文件中<mvc:annotation-driven  />开启之后,会给AnnotationMethodHandlerAdapter初始化7个转换器,可以通过调用AnnotationMethodHandlerAdapter的getMessageConverts()方法来获取转换器的一个集合 List<HttpMessageConverter>

    常用的转换器

    ByteArrayHttpMessageConverter 读写二进制数据
    StringHttpMessageConverter 将请求信息转换为字符串
    ResourceHttpMessageConverter 读写org.springframework.core.io.Resource对象
    SourceHttpMessageConverter 读写javax.xml.transform.Source类型的数据
    XMLAwareFormHttpMessageConverter 处理表单中的xml数据
    Jaxb2RootElementHttpMessageConverter 通过JAXB2读写XML消息,将请求消息转换到标准XmlRootElement和XmlType的注解类中
    MappingJacksonHttpMessageConverter 读写JSON数据

    后面三个分别用于处理xml数据和json数据,每次请求SpringMVC会从List<HttpMessageConverter>中挑选一个来处理数据,首先获取注册的所有HttpMessageConverter一个集合,然后会从客户的请求header中寻找客户端可接收的类型,比如application/json或者application/xml等组成一个集合,所有的HttpMessageConverter都有canRead()和canWrite()方法,返回的值都是布尔类型,看这个HttpMessageConverter是否支持当前请求的读与写,读对应的RequestBody注解,写对应的ResponseBody注解,RequestBody注解与RequestParam类似,主要用于读取请求的body数据。最后会遍历HttpMessageConverter集合,与前面获取可接受类型进行匹配,如果匹配,那么直接使用当前第一个匹配的HttpMessageConverter,然后return

    例子:

    在spring-mvc.xml配置

    <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager">
      <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
        <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
        <bean id="marshallingHttpMessageConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter" >
          <constructor-arg ref="jaxbMarshaller" />
          <property name="supportedMediaTypes" value="application/xml"></property>
        </bean>
      </mvc:message-converters>
    </mvc:annotation-driven>
        
    <bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
      <property name="classesToBound">
        <list>
          <value>com.jikexueyuan.demo.springmvc.model.User</value>
        </list>
      </property>
    </bean>

    通过使用ResponseBody注解,根据请求header中Accept参数值的不同,对同一地址请求分别来呈现一个实体的json与xml结果,首先在配置文件中,使用mvc:annotation-driven定义需要用到的messageConverter,这里我们用到了4个转换器,分别用来处理json数据、String数据、xml数据,在定义xml数据处理过程中需要使用Jaxb2Marshaller这个类来定义我们的实体类,比如User类,需要标明xmlRootElement注解

    java中converter实现

    // 使用ResponseBody注解进行标注,直接返回需要转换的对象
    @ResponseBody
    @RequestMapping(value="/user/{userid}", method = RequestMethod.GET)
    public User queryUser(@PathVariable("userid") long userId) {
      User u = new User();
      u.setUnick("zhangsan");
      u.setLastLoginDateTime(new Date());
      return u;
    }
    • RequestHeader

      @RequestHeader注解,可以把Request请求header部分的值绑定到方法的参数上。使用于方法参数上@RequestHeader(“Keep-Alive”) long keepAlive

    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

  • 相关阅读:
    cf914D. Bash and a Tough Math Puzzle(线段树)
    RNQOJ [stupid]愚蠢的矿工(树形依赖背包)
    BZOJ4552: [Tjoi2016&Heoi2016]排序(线段树 二分)
    多项式系数学习笔记
    BZOJ4653: [Noi2016]区间(线段树 双指针)
    洛谷P3372 【模板】线段树 1(树状数组)
    BZOJ3261: 最大异或和(可持久化trie树)
    BZOJ4260: Codechef REBXOR (01Tire树)
    Android 关于显示键盘,布局错乱网上顶的问题
    Java 输入流读取文本文件换行符问题
  • 原文地址:https://www.cnblogs.com/xiaobaizhiqian/p/8127252.html
Copyright © 2011-2022 走看看