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

SpringMVC配置字符串绑定日期对象

2015-08-31 09:39 549 查看

1. controller中局部绑定

步骤一:编写转换器,前端字符串转化为日期对象

public class DateEditor extends PropertyEditorSupport {

private final DateFormat dateFormat;
private final boolean allowEmpty;
private final int exactDateLength;

/**
* Create a new DateEditor instance, using the given DateFormat
* for parsing and rendering.
*/
public DateEditor(DateFormat dateFormat, boolean allowEmpty) {
this.dateFormat = dateFormat;
this.allowEmpty = allowEmpty;
this.exactDateLength = -1;
}

/**
* Create a new DateEditor instance, using the given DateFormat
* for parsing and rendering.
*/
public DateEditor(DateFormat dateFormat, boolean allowEmpty, int exactDateLength) {
this.dateFormat = dateFormat;
this.allowEmpty = allowEmpty;
this.exactDateLength = exactDateLength;
}

/**
* Parse the Date from the given text, using the specified DateFormat.
*/
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (this.allowEmpty && !StringUtils.hasText(text)) {
// Treat empty String as null value.
setValue(null);
}
else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
throw new IllegalArgumentException(
"Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
}
else {
try {
long dateLong = Long.parseLong(text);
text = this.dateFormat.format(new Date(dateLong));
} catch (Exception ex) {
// 输入文本非long型
}
try {
setValue(this.dateFormat.parse(text));
} catch (ParseException ex) {
setValue(null);
}
}
}

/**
* Format the Date as String, using the specified DateFormat.
*/
@Override
public String getAsText() {
Date value = (Date) getValue();
return (value != null ? this.dateFormat.format(value) : "");
}

}


步骤二:在要转化的controller中注册

/**
* 绑定日期格式
*
* @param res 资源请求
* @param binder 资源绑定
*/
@InitBinder
public void initBinder(HttpServletRequest res, WebDataBinder binder) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
binder.registerCustomEditor(Date.class, new DateEditor(sdf, false));
}


2. 配置全局日期转换器

新版的Spring3.1.x之后,配置全局转换器有所不同。

步骤一:编写全局日期转换器

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
public class DateConverter implements Converter<String, Date> {

private static final SimpleDateFormat DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat TIMEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final SimpleDateFormat TIMEFORMAT2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

@Override
public Date convert(String source) {
//   SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

if (!StringUtils.hasText(source)) {
return null;
}

try {
SimpleDateFormat dateFormat = getDateFormat(source);
dateFormat.setLenient(false);
return dateFormat.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 功能:用本地的三种日期格式实例化出DateFormat对象
*
* @param value 待解析的值
* @return DateFormat对象
*/
private SimpleDateFormat getDateFormat(String value){
SimpleDateFormat dateFormat = null;

Pattern patter = null;
Matcher matcher = null;
String formatter = null;

try{
// ^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$
// yyyy-mm-dd
patter = Pattern.compile("^\\d{4}\\-\\d{1,2}\\-\\d{1,2}$");
matcher = patter.matcher(value);
if (matcher.matches()) {
dateFormat = DATEFORMAT;
formatter = "yyyy-mm-dd";
//System.out.println("yyyy-mm-dd");
return dateFormat;
}

// yyyy-MM-dd HH:mm:ss
patter = Pattern.compile("^\\d{4}\\-\\d{1,2}\\-\\d{1,2}\\s{1}\\d{1,2}:\\d{1,2}:\\d{1,2}$");
matcher = patter.matcher(value);
if (matcher.matches()) {
dateFormat = TIMEFORMAT;
formatter = "yyyy-MM-dd HH:mm:ss";
//System.out.println("yyyy-MM-dd HH:mm:ss");
return dateFormat;
}

// yyyy/MM/dd HH:mm:ss
patter = Pattern.compile("^\\d{4}\\/\\d{1,2}\\/\\d{1,2}\\s{1}\\d{1,2}:\\d{1,2}:\\d{1,2}$"); // yyyy-MM-dd HH:mm:ss
matcher = patter.matcher(value);
if (matcher.matches()) {
dateFormat = TIMEFORMAT2;
formatter = "yyyy/MM/dd HH:mm:ss";
//System.out.println("yyyy/MM/dd HH:mm:ss");
return dateFormat;
}

if (!StringUtils.hasText(formatter)) {
throw new IllegalArgumentException("cannot parse value[" + value + "] to date");
}
}catch(PatternSyntaxException se){
throw se;
}

return dateFormat;
}


步骤二:在配置文件中进行配置

(1)
<mvc:annotation-driven />
中配置中的
AnnotationMethodHandlerAdapter
已经配置了
webBindingInitializer

我们可以通过设置其属性
conversionService
来实现自定义类型转换

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.doje.XXX.web.DateConverter" />     <!-- 转换器实现类 -->
</list>
</property>
</bean>


(2) 修改spring service context xml配置文件中的annotation-driven,增加属性conversion-service指向新增的conversionService bean

<mvc:annotation-driven conversion-service="conversionService" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息