register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="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%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="init_binder/test1" method="post">
dob:<input type="text" name="dob"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
User.java
public class User implements Serializable{
private long id;
private String name;
private int age;
private Date dob;
get/set...
}
方案一
IninBinderController.java
//解决类型转换问题
@RequestMapping("/init_binder")
@Controller
public class IninBinderController {
//转换方法 将外部拿到的字符串转换为--->Date类型 第一种方案
@InitBinder //加上就会自动执行
public void convertion(WebDataBinder binder){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//因为外部传进来的就是这种结构
//true表示允许为空
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
@RequestMapping("/test1")
public String test1(User u) {
System.out.println("IninBinderController test1()...");
System.out.println("u="+u.getDob());
return "test";
}
}
方案二
StringToDateConverter.java
//转换的方案二
public class StringToDateConverter implements Converter<String, Date>{//自己定义,把String转为Date
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date convert(String str) {
Date date = null;
try {
if(str!=null&&!"".equals(str.trim())){
date = dateFormat.parse(str);
}
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
}
spring的配置文件:例如spring的一个工厂类,产生一个转换服务,同时把我们自己的转换器注入进去,可以有多个
<!--转换服务-->
<bean name="formatService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.briup.web.converter.StringToDateConverter"></bean>
</set>
</property>
</bean>
//在mvc标签中指定这个转换服务器
<mvc:annotation-driven conversion-service="formatService"/>
IninBinderController.java
//解决类型转换问题
@RequestMapping("/init_binder")
@Controller
public class IninBinderController {
@RequestMapping("/test1")
public String test1(User u) {
System.out.println("IninBinderController test1()...");
System.out.println("u="+u.getDob());
return "test";
}
}
方案三
public class User implements Serializable{
private long id;
private String name;
private int age;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date dob;
get/set...
}