springMVC学习(四)JSON传递

接收、返回JSON

  • 导入fastjson开发包

  • 配置JSON适配器(注解驱动模式)

<!--注解驱动-->
<mvc:annotation-driven>
   <!-- register-defaults="true"表示使用默认的消息转换器 -->
   <mvc:message-converters register-defaults="true">
       <!-- fastjson适配器 -->
       <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
           <property name="supportedMediaTypes">
               <list>
           <!-- 这里顺序不能反,一定先写text/html,不然IE执行AJAX时,返回JSON会出现下载文件 -->
                   <value>text/html;charset=UTF-8</value>
                   <value>application/json;charset=UTF-8</value>
                   <value>application/xml;charset=UTF-8</value>
               </list>
           </property>
           <property name="fastJsonConfig">
               <bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
                   <property name="features">
                       <list>
                           <value>AllowArbitraryCommas</value>
                           <value>AllowUnQuotedFieldNames</value>
                           <value>DisableCircularReferenceDetect</value>
                       </list>
                   </property>
                   <property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
               </bean>
           </property>
       </bean>
   </mvc:message-converters>
</mvc:annotation-driven>

使用两个注解

  • @RequestBody,作用在形参列表上,用于将前台发送过来固定格式的数据【xml 格式或者 json等】封装为对应的 JavaBean 对象,封装时使用到的一个对象是系统默认配置的 HttpMessageConverter进行解析,然后封装到形参上

  • @ResponseBody,作用在方法上的,@ResponseBody 表示该方法的返回结果直接写入 HTTP response body 中,一般在异步获取数据时使用【也就是AJAX】,在使用 @RequestMapping后,返回值通常解析为跳转路径,但是加上 @ResponseBody 后返回结果不会被解析为跳转路径,而是直接写入 HTTP response body 中。@ResponseBody就可以理解成将java的对象转换成json字符串的格式给前端解析(json数据格式解析比较简单)。如果不加,就走视图解析器,返回页面

    @RequestMapping(value = "/json.action")
   public @ResponseBody User jsonTest(@RequestBody User user){
       user.setId("2");
       return user;
  }

使用postman请求时,设置 Content-Type:application/json;charset=utf-8

HttpMessageConverter

在使用 <mvc:annotation-driven />标签配置时,默认配置了RequestMappingHandlerAdapter,并配置了一下默认的HttpMessageConverter

  • ByteArrayHttpMessageConverter: 负责读取二进制格式的数据和写出二进制格式的数据;

  • StringHttpMessageConverter: 负责读取字符串格式的数据和写出二进制格式的数据;

  • ResourceHttpMessageConverter:负责读取资源文件和写出资源文件数据;

  • FormHttpMessageConverter: 负责读取form提交的数据(能读取的数据格式为 application/x-www-form-urlencoded,不能读取multipart/form-data格式数据);负责写入application/x-www-from-urlencoded和multipart/form-data格式的数据;

  • MappingJacksonHttpMessageConverter: 负责读取和写入json格式的数据;

  • SouceHttpMessageConverter: 负责读取和写入 xml 中javax.xml.transform.Source定义的数据;

  • Jaxb2RootElementHttpMessageConverter: 负责读取和写入xml 标签格式的数据;

  • AtomFeedHttpMessageConverter: 负责读取和写入Atom格式的数据;

  • RssChannelHttpMessageConverter: 负责读取和写入RSS格式的数据;

当使用@RequestBody和@ResponseBody注解时,RequestMappingHandlerAdapter就使用它们来进行读取或者写入相应格式的数据

参数绑定

springmvc的参数绑定有以下几种方法:

1)默认的参数绑定 Request Response Session Model(实现ModelMap)

2)简单类型参数绑定 方法的形参上(Integer,String,Double,Boolean)

3)pojo类型

4)包装类型 QueryVo

5)参数绑定之自定义参数转换

高级参数绑定 1)绑定数组 直接在方法的参数上绑定 xxx[] xxx 将数组注入对象,用该对象来接受数组

2)绑定list 使用包装类,包装类中有list集合

自定义参数转换步骤(不再使用@InitBinder注解)

  • 定义转换类,实现Conveter接口

public class DateConverter implements Converter<String, Date> {
   @Override
   public Date convert(String s) {
       try {
           return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(s);
      } catch (ParseException e) {
           e.printStackTrace();
           return null;
      }
  }
}
public class StringTrimConverter implements Converter<String,String> {
   @Override
   public String convert(String s) {
       return s.trim();
  }
}
  • 配置转换器(基于注解驱动)

    <!--自定义参数转换器-->
   <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
       <property name="converters">
           <list>
               <bean class="converters.DateConverter"/>
               <bean class="converters.StringTrimConverter"/>
           </list>
       </property>
   </bean>
   <!--注解驱动-->
   <mvc:annotation-driven conversion-service="conversionService">

@RequestParam注解

如果前端传递的参数名称和业务方法中的参数名称不一样,就需要使用@RequestParam注解(在方法形参前使用),该注解有三个变量

  • value,指定前端传递的属性名称

  • required,是否必须要有该参数

  • defaultvalue,设置默认值

数据回显

提交后,如果出现错误,将刚才提交的数据回显到刚才的提交页面,就需要用到数据回显,有以下几种回显方法:

  • springmvc默认对pojo数据进行回显:springmvc默认支持pojo数据回显,springmvc自动将形参中的pojo重新放回request域中,request的key为pojo的类名(首字母小写),jsp页面调用

<input name="pojo的属性名" value="${pojo.属性名}">
  • 如果key不是pojo的类名(首字母小写),可以使用@ModelAttribute完成数据回显

//相当于 model.addAttribute("item", itemsCustom)
public String editItemSubmit(Model model,@ModelAttribute("item") ItemsCustomitemsCustom)

jsp页面调用

<input name="item的属性名" value="${item.属性名}">
  • 简单类型数据回显,最简单方法是使用model。model.addAttribute("id", id)

  • 如果要回显的数据是公共的,在方法上使用@ModelAttribute,就不用在每一个controller方法通过Model将数据传到页面

    //单独将商品类型的方法提出来
   @ModelAttribute("itemsType")
   public Map<String,String> getItemsType(){
       Map<String,String> itemsType=new HashMap<>();
       itemsType.put("1","数码");
       itemsType.put("2","服装");
       return itemsType;
  }

文件上传

添加依赖

  • commons-fileupload-1.2.2.jar

  • commons-io-2.4.jar

配置文件上传解析器

    <!--文件上传配置-->
   <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
       <!-- 设置上传文件的最大尺寸为5MB和编码 -->
       <property name="maxUploadSize" value="5242880"/>
       <property name="defaultEncoding" value="UTF-8"/>
   </bean>

controller

    @RequestMapping("/upload.action")
   public void upload(MultipartFile picture){
       //MultipartFile该对象就是封装了图片文件
       System.out.println(picture.getOriginalFilename());
  }

jsp

<form action="/upload.action" method="post" enctype="multipart/form-data" >
   <input type="file" name="picture">
   <input type="submit" value="submit">
</form>

 

原文地址:https://www.cnblogs.com/yjh1995/p/14164373.html