虽然SpringMVC可以自动绑定多种数据类型,但是有时候有些特殊的数据类型还是会在绑定时发生错误,需要我们自己书写类型转换完成绑定。

SpringMVC中提供两种绑定方式:以时间转换为例

1、属性编辑器(传统方式)

控制器:

 @RequestMapping(value="/login.do")
public String login(UserBean user){
log.info(user.getUsername());
log.info(user.getBirthday());
return "index";
}
// 自定义一个属性编辑器,用于转换时间类型
@InitBinder
public void converterStringDate(WebDataBinder binder){
binder.registerCustomEditor(Date.class, new DateEditor());
}

可以通过重写PropertyEditorSupport中的setAsText()定义自己的转换规则

 package com.cy.springannotation.controller;

 import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; public class DateEditor extends PropertyEditorSupport { @Override
public void setAsText(String text) throws IllegalArgumentException {
Date date = null;
try {
if(text.contains("-")){
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
date = sf.parse(text);
}else {
SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy");
date = sf.parse(text);
}
} catch (ParseException e) {
e.printStackTrace();
}
this.setValue(date);
} }

2、类型转换器

Converter是Spring3提供的新的类型转换,相对于属性转换器更强大,可以把任意类型转换,而不是局限于String类型。
 
控制器:
 @RequestMapping(value="/login.do")
public String login(UserBean user){
log.info(user.getUsername());
log.info(user.getBirthday());
return "index";
}
全局类型转换器
 package com.cy.springannotation.controller;

 import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; import org.springframework.core.convert.converter.Converter;
/**
* 全局类型转换器
* @author acer
*
*/
public class DateConvert implements Converter<String, Date>{
@Override
public Date convert(String text) {
Date date = null;
try {
if(text.contains("-")){
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
date = sf.parse(text);
}else {
SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy");
date = sf.parse(text);
} } catch (ParseException e) {
e.printStackTrace();
}
return date;
} }

类型转换器需要在配置文件中配置:

 <!--开启注解  -->
<mvc:annotation-driven conversion-service="tc" /> <!--类型转换器工厂 --> <bean id="tc" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.cy.springannotation.controller.DateConvert" />
</list>
</property>
</bean>

共同的jsp页面:

 <%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>登录页面</title>
<script type="text/javascript" src="<%=basePath%>js/jquery-2.1.4.js"></script>
<script type="text/javascript"> </script>
</head>
<body>
<form action="login.do" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>出生日期</td>
<td><input type="text" name="birthday"/></td>
</tr>
<tr>
<td colspan="2"> <input type="submit" value="提交"/> </td>
</tr>
</table>
</form>
</body>
</html>

结果显示:

Spring MVC 之类型转换(五)的更多相关文章

  1. 2017.3.31 spring mvc教程(五)Action的单元测试

    学习的博客:http://elf8848.iteye.com/blog/875830/ 我项目中所用的版本:4.2.0.博客的时间比较早,11年的,学习的是Spring3 MVC.不知道版本上有没有变 ...

  2. Spring mvc参数类型转换

    1,需求 有时候我们接收到的参数为String类型的,但是我们需要将它们转化为其他类型的如:date类型,枚举类型等等,spring mvc为我们提供了这样的功能. 2,配置文件 在springmvc ...

  3. spring mvc 参数类型转换

    实现方式以字符串转Date为例说明: 全局配置 第一种:实现 Converter 接口 实现类: public class StringToDateConveter implements Conver ...

  4. Spring MVC学习(五)---ModelAndView没有明显申明name

    看图不解释: 对于这种写法: new ModelAndView().addObject(XXX)  

  5. spring笔记2 spring MVC的基础知识2

    2,spring MVC的注解驱动控制器,rest风格的支持 作为spring mvc的明星级别的功能,无疑是使得自己的code比较优雅的秘密武器: @RequestMapping处理用户的请求,下面 ...

  6. spring笔记1 spring MVC的基础知识1

    1,spring MVC的流程 优秀的展现层框架-Spring MVC,它最出彩的地方是注解驱动和支持REST风格的url.   流程编号 完成的主要任务 补充 1 用户访问web页面,发送一个htt ...

  7. Spring MVC 教程,快速入门,深入分析

    http://elf8848.iteye.com/blog/875830/ Spring MVC 教程,快速入门,深入分析 博客分类: SPRING Spring MVC 教程快速入门  资源下载: ...

  8. Spring MVC 教程

    目录  一.前言二.spring mvc 核心类与接口三.spring mvc 核心流程图 四.spring mvc DispatcherServlet说明 五.spring mvc 父子上下文的说明 ...

  9. (转)Spring MVC

    资源下载: Spring_MVC_教程_快速入门_深入分析V1.1.pdf SpringMVC核心配置文件示例.rar 作者:赵磊 博客:http://elf8848.iteye.com 目录 一.前 ...

随机推荐

  1. 测试Animation大型动画文件拆分播放的可行性

    最近遇到一个问题,剧情动画文件大了复杂了之后,每次修改输出很麻烦,导出fbx就需要20分钟. 所以我想到了一个比较好的解决方法,在unity这边解决.把动画文件拆分成若干份,然后赋予不同的层并行播放 ...

  2. awk用法小结(作者总结)

    http://www.chinaunix.net/old_jh/24/691456.html http://wenku.baidu.com/view/ebac4fc658f5f61fb736664d. ...

  3. Firefox浏览器设置字符编码格式

    按照网上说的:工具 -> 选项 -> 内容 -> 字体&颜色 -> 高级 -> 字体编码,根本没有找到utf-8,还是把浏览器定制一下吧,看源文件的时候也可以用, ...

  4. linux 内核手动编译

    手动编译内核 编译时后应安装的支持yum install perlyum install bcyum insatll gcc-c++ .uname -r 先查看内核版本 .yum groupinsta ...

  5. 编写shell管理脚本(一)

    7.1  查看当前linux系统中能够使用的shell程序的列表[root@localhost ~]# cat /etc/shells/bin/sh/bin/bash/sbin/nologin/bin ...

  6. 安卓开发之json解析

    1.从网页获取json返回字符串 public class ReadNet extends AsyncTask<URL, Integer, String> { @Override      ...

  7. POJ 2533 Longest Ordered Subsequence 最长递增序列

      Description A numeric sequence of ai is ordered if a1 < a2 < ... < aN. Let the subsequenc ...

  8. 六、IO流——文件

    IO流1.字节流(InputStream.OutputStream)2.字符流 (Reader.Writer)3.缓冲流(BufferedInputStream.BufferedOutputStrea ...

  9. [C程序设计语言]第二部分

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  10. ctrl+z暂停任务

    (1) CTRL+Z挂起进程并放入后台 (2) jobs 显示当前暂停的进程 (3) bg %N 使第N个任务在后台运行(%前有空格) (4) fg %N 使第N个任务在前台运行 默认bg,fg不带% ...