Spring MVC 数据转换和格式化


HttpMessageConverter和JSON消息转换器

HttpMessageConverter是定义从HTTP接受请求信息和应答给用户的
HttpMessageConverter是一个比较广的设计,虽然Spring MVC实现它的类有很多种,但是真正在工作和学习中使用得比较多的只有MappingJackson2HttpMessageConverter,这是一个关于JSON消息的转换类,通过它能够把控制器返回的结果在处理器内转换为JSON数据

代码清单16-3:使用XML配置MappingJackson2HttpMessageConverter

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonConverter"/>
        </list>
    </property>
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
            <value>application/json;charset=UTF-8</value>
        </list>
    </property>
</bean>

对于它的应用十分简单,只需要一个注解@ResponseBody就可以了。当遇到这个注解的时候,Spring MVC就会将应答类型转变为JSON,然后就可以通过响应类型找到配置的MappingJackson2HttpMessageConverter进行转换了

@RequestMapping(value = "/getRole3")
//注解,使得Spring MVC把结果转化为JSON类型响应,进而找到转换器
@ResponseBody
public Role getRole3(Long id) {
    // Role role = roleService.getRole(id);
    Role role = new Role(id, "射手", "远程物理输出");
    return role;
}

一对一转换器(Converter)

Converter是一种一对一的转换器
代码清单16-6:字符串角色转换器

package com.ssm.chapter15.converter;

import com.ssm.chapter15.pojo.Role;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

public class StringToRoleConverter implements Converter<String, Role> {

    @Override
    public Role convert(String str) {         //空串
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        //不包含指定字符
        if (str.indexOf("-") == -1) {
            return null;
        }
        String[] arr = str.split("-");
        //字符串长度不对
        if (arr.length != 3) {
            return null;
        }
        Role role = new Role();
        role.setId(Long.parseLong(arr[0]));
        role.setRoleName(arr[1]);
        role.setNote(arr[2]);
        return role;
    }

}

代码清单16-8:使用XML配置自定义转换器

<mvc:annotation-driven conversion-service="conversionService"/>

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="com.ssm.chapter15.converter.StringToRoleConverter"/>
        </list>
    </property>
</bean>

代码清单16-9:测试自定义转换器

@RequestMapping(value = "/updateRole")
@ResponseBody
public Role updateRole(Role role) {
    System.out.println(role.toString());
    // Map<String, Object> result = new HashMap<String, Object>();
    //更新角色
    // boolean updateFlag = (roleService.updateRole(role) == 1);
    // boolean updateFlag = false;
    // result.put("success", updateFlag);
    // if (updateFlag) {
    //     result.put("msg", "更新成功");
    // } else {
    //     result.put("msg", "更新失败");
    // }
    // return result;
    return role;
}

数组和集合转换器GenericConverter

上述的转换器是一种一对一的转换,它存在一个弊端:只能从一种类型转换成另一种类型,不能进行一对多转换,比如把String转换为List或者String[],甚至是List,一对一转换器都无法满足。为了克服这个问题,Spring Core项目还加入了另外一个转换器结构GenericConverter,它能够满足数组和集合转换的要求。

使用格式化器(Formatter)

有些数据需要格式化,比如说金额、日期等。传递的日期格式为yyyy-MM-dd或者yyyy-MM-dd hh:ss:mm,这些是需要格式化的,对于金额也是如此,比如1万元人民币,在正式场合往往要写作¥10 000.00,这些都要求把字符串按照一定的格式转换为日期或者金额。
为了对这些场景做出支持,Spring Context提供了相关的Formatter。它需要实现一个接口——Formatter
在Spring内部用得比较多的两个注解是@DateTimeFormat和@NumberFormat
代码清单16-16:测试数据转换的控制器

package com.ssm.chapter15.controller;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

@Controller
@RequestMapping("/convert")
public class ConvertController {

    @RequestMapping("/format")
    public ModelAndView format(
            //日期格式化
            @RequestParam("date1") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date date,
            //金额格式化
            @RequestParam("amount1") @NumberFormat(pattern = "#,###.##") Double amount) {
        ModelAndView mv = new ModelAndView("index");
        mv.addObject("date", date);
        mv.addObject("amount", amount);
        return mv;
    }

}


原文链接:https://www.cnblogs.com/ooo0/p/11128648.html