struts2自定义局部类型转换器

因为JSP中提交的表单是字符串类型,action中须要得到Date类型。虽然struts2内置的类型转换能够把"yyyy-MM-dd"转换成Date类型,然而,输入其余格式例如"MM/dd/yyyy"则不能转换,故此时须要自定义局部类型转换器将"MM/dd/yyyy"格式转换成Date类型。java

因为使用Date类型的action名为StockRequestaction,里面的startDate和endDate是Date类型,故新建StockRequestAction-converter.propertise(注意,这个文件必定要和StockRequestaction文件夹路径相同,即放在action目录下)ide

StockRequestAction-converter.propertisecode

startDate=com.dl.converter.DateConverter
endDate=com.dl.converter.DateConverter

src下新建converter包,converter包中新建DateConverter.java,编写转换器orm

package com.dl.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;

public class DateConverter extends DefaultTypeConverter{
	@Override
	public Object convertValue(Map<String, Object> context, Object value, Class toType){
		SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		try{
			if(toType == Date.class){
				String[] params = (String[])value;
				return dateFormat.parse(params[0]);
			}else if(toType == String.class){
				Date date = (Date) value;
				return dateFormat.format(date);
			}
		}catch (ParseException e){}
		return null;
	}
}
相关文章
相关标签/搜索