struts2 自定义局部类型转换器

来源:互联网 发布:高级编程语言有哪些 编辑:程序博客网 时间:2024/05/21 02:33

在HelloWorldAction中加入Date型成员变量birthday

url 通过get方法传入参数http://localhost:8080/Struts2/test3/income.action?birthday=2012-03-30

则birthday接受并打印在jsp里的值为Fri Mar 30 00:00:00 CST 2012

如果传入的值为http://localhost:8080/Struts2/test3/income.action?birthday=20120330

则birthday接受并打印在jsp里的值为20120330

解决该问题的方法为:使用类型转换器

在src中建立一个新包,在包里新建DateTypeConverter.java,内容如下:

// ---------------------------------------------------------// @author    sheng.xu// @version   1.0.0// @date2014年6月6日// ---------------------------------------------------------package cn.xs.type.converter;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Map;import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;/** * @author sheng.xu * */public class DateTypeConverter extends DefaultTypeConverter{@Overridepublic Object convertValue(Map<String, Object> context, Object value, Class toType) {SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");try { if(toType == Date.class){//当字符串向Date类型转换时String[] params = (String[]) value;// request.getParameterValues() return dateFormat.parse(params[0]);}else if(toType == String.class){//当Date转换成字符串时Date date = (Date) value;return dateFormat.format(date);}} catch (Exception e) {}return null;}}
在Action类所在的包下放置ActionClassName-conversion.properties文件,ActionClassName是Action的类名,-conversion.properties是固定写法,本例中应写成HelloWorldAction-conversion。内容如下:
birthday=cn.xs.type.converter.DateTypeConverter //<span style="font-family: Arial, Helvetica, sans-serif;">cn.xs.type.converter为报名</span>

再次访问就可以解决

0 0
原创粉丝点击