struts自定义类型转换器,局部和全局

来源:互联网 发布:jquery怎么渲染数据 编辑:程序博客网 时间:2024/05/17 03:58

我们在使用struts开发项目时可能或多或少会遇到自定义类型的转换问题,这时就需要自定义类型转换器.例如我们将对象内容字符串转换为对象

第一步:写一个转换类,这个类需要继承DefaultTypeConverter(import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;xworkjar包也可以):

测试action:

package com.leige.demo;import java.util.Date;import com.opensymphony.xwork2.ActionSupport;public class Hello2 extends ActionSupport {private Date birthday;public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String hello2(){return "conversion";}}


例如日期和字符串的转换:
20120706-日期:

日期-字符串:

package com.leige.demo;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Map;import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;public class DateConvert extends DefaultTypeConverter {@Overridepublic Object convertValue(Map<String, Object> context, Object value,Class toType) {// TODO Auto-generated method stubSimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");try{if(toType==Date.class){//从字符串转换为日期//struts接收参数是以数组的形式String params[]=(String[]) value;return dateFormat.parse(params[0]);}else if(toType==String.class){return dateFormat.format((Date)value);}}catch (Exception e) {// TODO: handle exception}return null;}}

这个可以放置在其他路径下:


2:设置配置文件

局部类型转换器必须放置在被处理action的包下,命名规则是ActionClassName-conversion.properties

配置文件中填写转换属性和转换操作类:


2:全局类型转换器放置在src目录下:

名称xwork-conversion.properties而内容中写对应类型和要是用的转换类

配置如下:


然后命名为xwork-conversion.properties放置在src下



0 0