课时13
- 自定义类型转换器
局部(对某个action类)
1 package tutorial; 2 3 import java.util.Date; 4 5 public class HelloWorld { 6 private Date birthday; 7 8 public Date getBirthday() { 9 return birthday; 10 } 11 12 public void setBirthday(Date birthday) { 13 System.out.println(birthday); 14 this.birthday = birthday; 15 } 16 17 public String execute(){ 18 return "success"; 19 } 20 21 public String add(){ 22 return "success"; 23 } 24 }
1 package type; 2 3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 import java.util.Map; 6 7 8 import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter; 9 10 public class DateTypeConverter extends DefaultTypeConverter { 11 12 @Override 13 public Object convertValue(Map<String, Object> context, Object value, 14 Class toType) { 15 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd"); 16 try { 17 if(toType == Date.class) { //字符串转Date类型 18 String[] param = (String[]) value; 19 return dateFormat.parse(param[0]); 20 } else if (toType == String.class) { //Date转字符串 21 Date date = (Date) value; 22 return dateFormat.format(date); 23 } 24 }catch (java.text.ParseException e) { } 25 26 return null; 27 } 28 29 }
将上面的类型转换器注册为局部类型转换器:
在Action类所在的包下放置ActionClassName-conversion.properties文件,ActionClassName是Action的类名,后面的-conversion.properties是固定写法,对于本例而言,文件的名称应为HelloWorldAction-conversion.properties 。在properties文件中的内容为:
属性名称=类型转换器的全类名(birthday=type.DateTypeConverter)

课时14
- 自定义全局类型转换器(对整个应用)
将上面的类型转换器注册为全局类型转换器:
在WEB-INF/classes下放置xwork-conversion.properties文件 。在properties文件中的内容为:待转换的类型=类型转换器的全类名
对于本例而言, xwork-conversion.properties文件中的内容为:
java.util.Date=type.DateTypeConverter
浙公网安备 33010602011771号