定义一个测试类
package struts2.example.action;
import java.util.Date;
public class HelloWorldAction {
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
System.out.print(birthday);
this.birthday = birthday;
}
public String execute() throws Exception{
return "success";
}
}
在struts.xml文件里定义
<action name="list_*" class="struts2.example.action.HelloWorldAction" method="{1}">
<!-- 定义处理结果与视图资源之间的关系 -->
<result name="success">/index.jsp</result>
</action>
运行时在网址输入http://localhost:端口号/工程名/..(命名空间)../list_execute.action?birthday=20121181即可完成跳转,在index.jsp通过el表达式 ${birthday }输出相应的birthday的值,输出的是带星期等其他信息的数据,不是原来的字符串。应用类型转换器能够实现数据的双向转换。
类型转换器分为两种
局部类型转换器:对某个action起作用
全局类型转换器:对所有的action起作用
所谓类型转换器就是继承一个类DefaultTypeConverter,然后重写方法实现。应用类型转换器会有两种情况:
1、由请求参数的值转换成属性的值
2、使用struts2的标签,进行数据回显
package struts2.example.type.converter;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
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) {
// TODO Auto-generated method stub
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyNNdd");
try{
if(toType==Date.class){//将String类型转换成Date类型
String[] params=(String[]) value;
return simpleDateFormat.parse(params[0]);
}else if(toType==String.class){//将Date类型转换成String类型
Date date=(Date) value;
return simpleDateFormat.format(date);
}
}catch(ParseException e){
}
return null;
}
}
与Struts1一样,在Struts2中也需要注册。注册
局部类型转换器:
在action类所在的包下放置ActionClassName-conversion.properties文件,ActionClassName是
Action的类名,后面的-conversion.properties是固定写法,对于本例而言,文件的名称应
为HelloWorldAction.properties。
在properties文件中的内容为:属性名称=类型转换器的全类名
对于本例而言,HelloWorldAction-conversion.properties文件中的内容为:
birthday=struts2.example.type.converter.DateTypeConverter
自定义全局类型转换器:在WEB-INF/classes下放置xwork-conversion.properties文件,在properties文件中
的内容为:待转换的类型=类型转换器的全类名
对本例而言,xwork-conversion.properties文件中的内容为:
java.util.Date=struts2.example.type.converter.DateTypeConverter
另外,使用全局类型转换器要注意输入的数据格式符号要求。