package struts2.demo.action;
import java.util.Date;
public class DateAction {
private Date birthday;
public String execute(){
return "success";
}
public void setBirthday(Date birthday) {
System.out.println(birthday);
this.birthday = birthday;
}
public Date getBirthday() {
return birthday;
}
}
http://localhost:8080/Struts2/demo/date?birthday=2009-12-12
控制台和jsp页面均打印Sat Dec 12 00:00:00 CST 2009
■如果http://localhost:8080/Struts2/demo/date?birthday=20091212
则控制台会报错而jsp页面会原样打印
如果要接受此种格式日期.需要定义类型转换器
局部类型转换器,全局类型转换器
定义类型转换器需要继承DefaultTypeConverter类 通过重写其方法实现
package struts2.demo.action;
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 DateTypeConverter extends DefaultTypeConverter {
@Override
public Object convertValue(Map<String, Object> context, Object value,//接收到的值-需要进行转换的值
Class toType) {//要转换成的目标类型
SimpleDateFormat sim = new SimpleDateFormat("yyyyMMdd");
if(toType==Date.class){
String[] param=(String[])value;
try {
return sim.parse(param[0]);
} catch (ParseException e) {
e.printStackTrace();
}
}else if(toType==String.class){
Date date = (Date)value;
return sim.format(date);
}
return super.convertValue(context, value, toType);
}
}
将上面的类型转换器注册为局部类型转换器
在action类所在的包下放置ActionClassName-conversion.properties文件,actionClassName是Action的类名,后面的-conversion.properties是固定写法
properties文件中的内容为
属性名称=类型转换器的全类名
DateAction-conversion.properties
birthday=struts2.demo.action.DateTypeAction