您的位置:首页 > 编程语言 > Java开发

SpringMVC 自动绑定数据 - DATE多个类型格式 的数据绑定

2017-03-04 11:42 344 查看
总共方法有三种:

第一种:繁重操作解决方式:

在 Controller 里面不写 InitBinder 方法; 直接在请求实体类里面将DATE 类型的字段 注解 @DateTimeFormat("格式")

第二种:比较繁重操作解决方式:

在 Controller 里面写 InitBinder 方法; 里面写多个日期格式;将特殊的标出;如下代码:

@InitBinder
public void initBinder(WebDataBinder b) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
b.registerCustomEditor(Date.class, new CustomDateEditor(df, true));

DateFormat df2 = new SimpleDateFormat("yyyy-MM");
String[] fileds = {"字段名", "字段名", "字段名"};
for(String filed : fileds){
b.registerCustomEditor(Date.class, filed, new CustomDateEditor(df2, true));
}
}


第三种:轻松解决方式:

自己写一个DATE数据绑定类;然后在Controller 里面写 InitBinder 方法里面应用;如下代码

package com.luwen.dai.util;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SpecialDateEditor extends PropertyEditorSupport {

private final Logger logger = LoggerFactory.getLogger(getClass());

@Override
public void setAsText(String text) throws IllegalArgumentException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
//防止空数据出错
if(StringUtils.isNotBlank(text)){
date = format.parse(text);
}
} catch (ParseException e) {
format = new SimpleDateFormat("yyyy-MM-dd");
try {
date = format.parse(text);
} catch (ParseException e1) {
format = new SimpleDateFormat("yyyy-MM");

try{
date = format.parse(text);
}catch (Exception e2) {
logger.error("自动绑定日期数据出错", e);
}
}
}
setValue(date);
}

}


然后在initBinder 方法里直接引用

@InitBinder
public void initBinder(WebDataBinder b) {
b.registerCustomEditor(Date.class, new SpecialDateEditor());
}


 以上为 三种 SpringMVC 多个 日期格式 数据类型自动绑定解决方法;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: