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>或者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 数据转换和格式化的更多相关文章
- Spring mvc数据转换 格式化 校验(转载)
原文地址:http://www.cnblogs.com/linyueshan/p/5908490.html 数据绑定流程 1. Spring MVC 主框架将 ServletRequest 对象及目标 ...
- 0061 Spring MVC的数据格式化--Formatter--FormatterRegistrar--@DateTimeFormat--@NumberFormat
Converter只完成了数据类型的转换,却不负责输入输出数据的格式化工作,日期时间.货币等虽都以字符串形式存在,却有不同的格式. Spring格式化框架要解决的问题是:从格式化的数据中获取真正的数据 ...
- Spring MVC数据转换
样例:把一个字符串封装而一个对象. 如:username:password格式的数据ZhangSan:1234.我们把这个数据封装成一个User对象.以下分别使用属性编辑器与转换器来实现. 1.自己定 ...
- Spring MVC -- 转换器和格式化
在Spring MVC -- 数据绑定和表单标签库中我们已经见证了数据绑定的威力,并学习了如何使用表单标签库中的标签.但是,Spring的数据绑定并非没有任何限制.有案例表明,Spring在如何正确绑 ...
- spring mvc 数据转换
项目目录结构 User.java package org.mythsky.springmvcdemo.model; import org.springframework.format.annotati ...
- Spring MVC—数据绑定机制,数据转换,数据格式化配置,数据校验
Spring MVC数据绑定机制 数据转换 Spring MVC处理JSON 数据格式化配置使用 数据校验 数据校验 Spring MVC数据绑定机制 Spring MVC解析JSON格式的数据: 步 ...
- 第6章 Spring MVC的数据转换、格式化和数据校验
使用ConversionService转换数据 <%@ page language="java" contentType="text/html; charset=U ...
- Spring MVC基础知识整理➣数据校验与格式化
概述 将view中Form的数据提交到后台之后,后台如何验证数据的有效性?在这里Spring MVC提供了相应的Hibernate类包(hibernate-validator-4.3.1.Final. ...
- Spring MVC @InitBinder 数据绑定 & 数据格式化 & 数据校验
1 数据绑定 2 数据格式化 修改绑定的字段等等操作 日期 - 接收表单日期字符串格式内容.,在实体类加入@DateTimeFormat 数值 原理: DefautFormattingConversi ...
随机推荐
- 编程判断输入的字符是否为‘y’或‘Y’,若是,则输出‘yes’,否则输出‘no’
#include<stdio.h>void main(){ char ch; ch=getchar(); ch == 'y' || ch == 'Y' ? printf("yes ...
- [Kubernetes] Kubectl and Pod
1. Create and run a Pod kubectl run my-nginx --image=nginx:alpine We can run kubectl get all to see ...
- 第二章--MYSQL体系结构和管理
体系结构 MySQL C/S模型 Server : mysqld Client : socket:仅本地连接使用 tcp/ip:应用连接使用(远程和本地) #TCP/IP方式(远程.本地) mysql ...
- bzoj 5408: string 后缀自动机 + LCT
联赛前练练码力. code: #include <vector> #include <cstdio> #include <cstring> #include < ...
- learning java Runtime类中的exec
var rt = Runtime.getRuntime(); // 类c语言当中的system()函数. rt.exec("notepad.exe");
- CSS3 新增选择器:伪类选择器和属性选择器
一.结构(位置)伪类选择器( : ) 1.:first-child 2.:last-child 3.:nth-child(n)或者:nth-child(2n)或者:nth-child(2n+1) &l ...
- $\text{fhq-treap}$总结
\(\text{fhq-treap}\)总结 又名范浩强\(\text{treap}\),是一种无旋\(\text{treap}\).其原理同\(\text{treap}\)一样都是通过维护一个随机堆 ...
- mpvue搭建小程序框架
http://mpvue.com/mpvue/ 美团开源了mpvue 由于mpvue框架是完全基于Vue框架的(重写了其runtime和compiler) 运行时框架 runtime 和代码编译器 c ...
- 开源GIT仓库-----gogs
简介:Gogs 是一款极易搭建的自助 Git 服务,其目标是打造一个最简单.最快速和最轻松的方式搭建自助 Git 服务.使用 Go 语言开发使得 Gogs 能够通过独立的二进制分发,并且支持 Go 语 ...
- java读取文件内容并输出到控制台,java中实现文件复制
public class TestFileInputStream { public static void main(String [] args) { //读取指定文件中内容,并在控制台输出 Fil ...