- 如何自定义类型转换器:
1)为什么需要自定义类型转化器?strtuts2不能自动完成字符串到所有的类型;
2) 如何定义类型转化器?
步骤一:创建自定义类型转化器的类,并继承org.apache.struts2.util..StrutsTypeConverter类;
步骤二:配置类型转化器(包含两种方式:基于字段的配置、基于类型的配置)
官网有类型转化器的写用法向导:http://struts.apache.org/docs/type-conversion.html
备注:从官网向导中我们知道struts2.3.13之后,是支持date类型自动转化的,看到官网上很多说date类型不可以自动转化的就需要看看文档了。
Built in Type Conversion Support
Type Conversion is implemented by XWork.
XWork will automatically handle the most common type conversion for you. This includes support for converting to and from Strings for each of the following:
- String
- boolean / Boolean
- char / Character
- int / Integer, float / Float, long / Long, double / Double
- dates - uses the SHORT format for the Locale associated with the current request
- arrays - assuming the individual strings can be coverted to the individual items
- collections - if not object type can be determined, it is assumed to be a String and a new ArrayList is created
Note that with arrays the type conversion will defer to the type of the array elements and try to convert each item individually. As with any other type conversion, if the conversion can't be performed the standard type conversion error reporting is used to indicate a problem occurred while processing the type conversion.
- Enumerations
- BigDecimal and BigInteger
- 基于字段的配置
1、在字段所在的Model(可能是Action,可能是一个JavaBean)的报下,新建一个ModelClassName-conversion.properties;
2、在ModelClassName-conversion.properties内输入键值对:fieldName=类型转换器的全类名;
3、加载时:第一次使用该转换器时创建实例;
4、类型转换器在使用过程中只实例化一次,是单例的。
基于上一篇文章《》中例子上修改程序:
MyAction.java
/** * @author Administrator * */ package com.dx.actions; import java.awt.Point; import java.util.Date; import com.opensymphony.xwork2.ActionSupport; public class MyAction extends ActionSupport { private static final long serialVersionUID = 1L; private Integer age; private Date birth; private Point point; public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public Point getPoint() { return point; } public void setPoint(Point point) { this.point = point; } public String execute() { System.out.println("age:" + this.age + ",birth:" + this.birth + ",point:" + this.point); } }