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>或者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;
} }

Spring MVC 数据转换和格式化的更多相关文章

  1. Spring mvc数据转换 格式化 校验(转载)

    原文地址:http://www.cnblogs.com/linyueshan/p/5908490.html 数据绑定流程 1. Spring MVC 主框架将 ServletRequest 对象及目标 ...

  2. 0061 Spring MVC的数据格式化--Formatter--FormatterRegistrar--@DateTimeFormat--@NumberFormat

    Converter只完成了数据类型的转换,却不负责输入输出数据的格式化工作,日期时间.货币等虽都以字符串形式存在,却有不同的格式. Spring格式化框架要解决的问题是:从格式化的数据中获取真正的数据 ...

  3. Spring MVC数据转换

    样例:把一个字符串封装而一个对象. 如:username:password格式的数据ZhangSan:1234.我们把这个数据封装成一个User对象.以下分别使用属性编辑器与转换器来实现. 1.自己定 ...

  4. Spring MVC -- 转换器和格式化

    在Spring MVC -- 数据绑定和表单标签库中我们已经见证了数据绑定的威力,并学习了如何使用表单标签库中的标签.但是,Spring的数据绑定并非没有任何限制.有案例表明,Spring在如何正确绑 ...

  5. spring mvc 数据转换

    项目目录结构 User.java package org.mythsky.springmvcdemo.model; import org.springframework.format.annotati ...

  6. Spring MVC—数据绑定机制,数据转换,数据格式化配置,数据校验

    Spring MVC数据绑定机制 数据转换 Spring MVC处理JSON 数据格式化配置使用 数据校验 数据校验 Spring MVC数据绑定机制 Spring MVC解析JSON格式的数据: 步 ...

  7. 第6章 Spring MVC的数据转换、格式化和数据校验

    使用ConversionService转换数据 <%@ page language="java" contentType="text/html; charset=U ...

  8. Spring MVC基础知识整理➣数据校验与格式化

    概述 将view中Form的数据提交到后台之后,后台如何验证数据的有效性?在这里Spring MVC提供了相应的Hibernate类包(hibernate-validator-4.3.1.Final. ...

  9. Spring MVC @InitBinder 数据绑定 & 数据格式化 & 数据校验

    1 数据绑定 2 数据格式化 修改绑定的字段等等操作 日期 - 接收表单日期字符串格式内容.,在实体类加入@DateTimeFormat 数值 原理: DefautFormattingConversi ...

随机推荐

  1. 为什么要使用ConcurrentHashMap

    好久没写过技术性文章了,还是要坚持下去.掌握的知识,能写出来或者是讲给别人听才是真正的掌握了知识,如果不善于给别人讲,实际上还是没有真正掌握相关的知识,挑个简单的写吧. 面试的时候经常会被问到hash ...

  2. Oracle-分析函数之取上下行数据lag()和lead()

    这两个函数是偏移量函数,可以查出一个字段的上一个值或者下一个值,配合over来使用. lead函数,这个函数是向上偏移. lag函数是向下偏移一位. 语法 [语法] lag(EXPR,<OFFS ...

  3. HDU - 4507 - 吉哥系列故事——恨7不成妻(数位DP,数学)

    链接: https://vjudge.net/problem/HDU-4507 题意: 单身! 依然单身! 吉哥依然单身! DS级码农吉哥依然单身! 所以,他生平最恨情人节,不管是214还是77,他都 ...

  4. Zookeeper数据类型、节点类型、角色、watcher监听机制

    1.Zookeeper数据类型:层次化目录结构+少量数据 Zookeeper包含层次化的目录结构,每个Znode都有唯一的路径标识,Znode可以包含数据和子节点. 其中Znode数据可以有多个版本, ...

  5. (尚007)Vue强制绑定class和style

    注意:class和style的值是动态的值 1.test007.html <!DOCTYPE html><html lang="en"><head&g ...

  6. asp.net文件夹上传下载组件

    ASP.NET上传文件用FileUpLoad就可以,但是对文件夹的操作却不能用FileUpLoad来实现. 下面这个示例便是使用ASP.NET来实现上传文件夹并对文件夹进行压缩以及解压. ASP.NE ...

  7. 通过django-crontab扩展来实现 定时任务

    pip install django-crontab 基本格式 : * * * * * 分 时 日 月 周 命令 M: 分钟(0-59).每分钟用*或者 */1表示 H:小时(0-23).(0表示0点 ...

  8. nohup 后台执行

    nohup  默认是当前用户执行的,当当前用户退出会导致执行进程异常. 所以正确的 nohup 是指定 /bin/bash 进行执行. nohup /bin/bash/ /opt/script/s.s ...

  9. Processing中和值域相关的函数

    今天在群里有人问了个问题:请教下啊,群里能有高手讲讲norm(), lerp(), map()么,英文的实在是没看懂呀?鉴于很多人初学Processing都没弄明白这3个函数的用法,我这里简单介绍一下 ...

  10. Video Reviews

    题目链接:http://codeforces.com/gym/101755/problem/K 题目理解: 一家公司想让n个人给他们的产品评论,所以依次去找这n个人,第i个人会评论当且仅当已经有ai个 ...