Struts2之自定义类型转换器

1.自定义进行局部类型转换器

        1、在action类同一个文件夹下创建:action类名-conbersion.properties 文件(文件名固定),同样需要在成员变量类的同文件夹下创建:类名-conbersion.properties(同样固定),此文件夹下写的是要转换类型的成员变量。

   类名-conbersion.properties文件中内容:要转换类型的成员变量=类型转换器的全类名

birthday = com.beans.DateConverter

        2、创建类型转换的类例:DateConvertter.java(此类可以创建在与成员变量类同一个文件夹下)

注:只要类型不匹配抛出类型异常就会返回input视图

public class DateConverter extends DefaultTypeConverter{
	//value:将要被转换的值
	//toType:要转换成为的目标类型
	//页面-->服务器: String[] -->Date
	//服务器-->页面: Date -->String
	@Override
	public Object convertValue(Object value, Class toType) {
		SimpleDateFormat  sdf = null;
			try {
				if(toType==Date.class) {//成立说明是由页面到服务器的转换
					String dateStr = ((String[])value)[0];
					sdf = getSimpleDateFormat(dateStr);  //返回格式
					ActionContext.getContext().getSession().put("sdf", sdf);
					return sdf.parse(dateStr);
				}else if(toType==String.class) { //成立说明是由服务器到页面的转换
					Date date = (Date)value;
					sdf=(SimpleDateFormat) ActionContext.getContext().getSession().get("sdf");
					return sdf.format(date);
				}
			}catch(ParseException e) {
				e.printStackTrace();
			}
		return super.convertValue(value, toType);
	}
	private SimpleDateFormat getSimpleDateFormat(String dateStr) {
		//匹配多种自定义类型
		SimpleDateFormat sdf = null;
		if(Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", dateStr)) {
			sdf = new SimpleDateFormat("yyyy/MM/dd");
		}else if(Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", dateStr)) {
			sdf = new SimpleDateFormat("yyyy-MM-dd");
		}else if(Pattern.matches("^\\d{4}\\d{2}\\d{2}$", dateStr)) {
			sdf = new SimpleDateFormat("yyyyMMdd");
		}else {
			throw new TypeConversionException();
		}
		return sdf;
	}
}

2.自定义全局类型转换器

      全局类型转换需在WEB_INF/classes文件夹下创建一个xwork--conbersion.properties文件,文件内容为:待转换的类型=类型转换器的全类名。例:java.util.Date=com.beans.DateConverter   其他的均与局部类型转换器一样。

猜你喜欢

转载自blog.csdn.net/wangyang668/article/details/81349761