1、前言
表现层经常会接受页面表单的数据,springmvc框架提供了封装javaBean的功能,但是针对一些特殊的属性,则不会自动封装(比如java.util.Date类型),需要我们自行绑定。这里介绍两种解决的办法:@InitBinder&@DateTimeFormat()
2、@DateTimeFormat()绑定Date类型
@DateTimeFormat()实现数据的绑定比较简单,只需要在需要绑定类的属性上或者setter()方法上添加注解:@DateTimeFormat(pattern=“yyyy-MM-dd HH:mm:ss”)。此外该方法需要依赖单独的jar包:joda-time
<!-- 注解实例:-->
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date birthday;
<!-- 坐标依赖:-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>1.3</version>
</dependency>
但是在企业开发中的pojo类都是反向生成的,一般不会在pojo类中直接添加注释。因为如果业务需要重新生成pojo类,就会有可能覆盖该注解,会造成不必要的麻烦。
3、@InitBinder绑定表单
/*改代码可以直接使用*/
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.PropertiesEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
/**
*
* @author admin
*
*/
@Controller //这个注解是必须的
public class BaseController {
protected static final Logger LOGGER = LoggerFactory.getLogger(BaseController.class);
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new MyDateEditor());
/*
从PropertyEditorSupport 实现的方法可以看出,这里的绑定是为了处理空和null的数据,
开发者可根据实际情况绑定
*/
binder.registerCustomEditor(Double.class, new DoubleEditor());
binder.registerCustomEditor(Integer.class, new IntegerEditor());
}
private class MyDateEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
//通过两次异常的处理可以,绑定两次日期的格式
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(text);
} catch (ParseException e) {
format = new SimpleDateFormat("yyyy-MM-dd");
try {
date = format.parse(text);
} catch (ParseException e1) {
LOGGER.error("系统异常:"+e1);
}
}
setValue(date);
}
}
public class DoubleEditor extends PropertiesEditor {
@Override
public void setAsText(String text) throws IllegalArgumentException {
try {
if (text == null || text.equals("")) {
text = "0";
}
} catch (Exception e) {
LOGGER.error("系统异常:"+e);
}
setValue(Double.parseDouble(text));
}
@Override
public String getAsText() {
return getValue().toString();
}
}
public class IntegerEditor extends PropertiesEditor {
@Override
public void setAsText(String text) throws IllegalArgumentException {
try {
if (text == null || text.equals("")) {
text = "0";
}
} catch (Exception e) {
LOGGER.error("系统异常:"+e);
}
setValue(Integer.parseInt(text));
}
@Override
public String getAsText() {
return getValue().toString();
}
}
}
使用该注解就不会改变原有的pojo类。该注解的用法有两种:一种是针对某一个controller实现绑定,就是将@InitBinder下的方法直接写在一个controller下面即可;第二种可以针对整个项目,像实例一样抽出BaseController,让所有的controller继承BaseController,即可。这里没有指定固定的字段,程序会默认给属性为Date的字段绑定。
4、备注
有注解自然会有xml配置,可以自定义绑定器需要实现WebBindingInitializer接口,然后XML配置:
<!--
如果该配置文件中有<mvc:annotation-driven/>配置,下面的bean要配置在<mvc:annotation-driven/>之前,否则无效。
原因:
注解驱动中已经配置了RequestMappingHandlerAdapter和RequestMappingHandlerMapping。如果在注解驱动之后配置,就会无效。
-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="cacheSeconds" value="0" />
<property name="webBindingInitializer">
<!-- 自定义绑定 -->
<bean class="ws.spring.mybatis.web.MyBinderInitializer" />
</property>
</bean>
<!--
注解驱动中已经配置了RequestMappingHandlerAdapter和RequestMappingHandlerMapping。如果在注解驱动之前提前配置,就会覆盖注解驱动中的配置(注解驱动就不会加载)。
但是注解驱动中,加载的RequestMappingHandlerAdapter中还包含了jsonHttpMessageConverter,实现对象与json数据的转化。此时,就需要手动配置消息转化器了。
所以推荐使用注解@InitBinder。封装在BaseController中,直接继承。这就不会影响xml的配置了。
-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="cacheSeconds" value="0" />
<property name="webBindingInitializer">
<bean class="ws.spring.mybatis.web.MyBinderInitializer" />
</property>
<property name="messageConverters">
<list>
<ref bean="jsonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
在测试中,还有一种针对指定的字段的简单绑定:
@InitBinder
public void initBinder(WebDataBinder binder) {
DateFormat df = new SimpleDateFormat(datePattern);
CustomDateEditor editor = new CustomDateEditor(df, true);
binder.registerCustomEditor(Date.class,"birthday", editor);
}
/*
这里如果不指定字段名,获取的值为空。
*/