走进Struts2(四)— 自定义转换器

来源:互联网 发布:tomcat怎么连接数据库 编辑:程序博客网 时间:2024/05/17 09:41

尽管Struts2提供的内建类型转换器能满足绝大多数的需求,但是,有的时候还是需要使用自定义类型转换器来实现特定的需求。因为Struts2不能自动完成 字符串 到 引用类型 的 转换


需求:实现指定格式的日期转换 yyyy-MM-dd

1.准备 UserAcrion2类

@SuppressWarnings("serial")public class UserAction2 extends ActionSupport{private String name;private Integer age;private Date birth;public String getName() {return name;}public void setName(String name) {this.name = name;}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 String addUser(){System.out.println("User2");return SUCCESS;}}
2.index.jsp

</head><body><s:debug></s:debug><s:form action="addUser2" namespace="/user" method="get"><s:textfield name="name" label="姓名"  /><!--<s:property value="%{[0].name}"/>--><s:textfield name="age" label="年龄" /><s:textfield name="birth" label="出生日期"/><s:submit/></s:form></body></html>

3.自定义类型转换器需要 继承 StrutsTypeConverter

public class DateConversion extends StrutsTypeConverter {private DateFormat df = null;private DateFormat getDateFormat() {if (df == null) {ServletContext context = ServletActionContext.getServletContext();/** * 在 web.xml 定义 pattern 类型 */String pattern = context.getInitParameter("pattern");if (pattern == null || pattern.trim().isEmpty()) {pattern = "yyyy-MM-dd";}df = new SimpleDateFormat(pattern);}return df;}@Overridepublic Object convertFromString(Map arg0, String[] values, Class obj) {if (obj == Date.class) {if (values != null && values.length > 0) {String value = values[0];try {System.out.println(getDateFormat().parseObject(value));return getDateFormat().parseObject(value);} catch (ParseException e) {throw new RuntimeException(e);}}}return values;}@Overridepublic String convertToString(Map arg0, Object obj) {if (obj instanceof Date) {Date date = (Date) obj;return getDateFormat().format(date);}return null;}}

4.进行配置

类型转换配置方法有两种:

一、基于字段的配置

1.在字段所在的 Model( Action / JavaBean) 的包下, 新建一个 ModelClassName-conversion.properties 文件

2.输入键值对: fieldName=类型转换器的全类名.

文件名 UserAction2-conversion.propertiesbirth=cn.cil.conversion.DateConversion


PS:第一次使用该转换器时创建实例,所以类型转换器是单实例的!

二、基于类型的配置

把UserAction2只的属性抽取组成一个javaBean。

public class UserAction extends ActionSupport implements ModelDriven<User>{private User user = new User();public User getUser() {return user;}public void setUser(User user) {this.user = user;}public String addUser(){System.out.println("User1");return SUCCESS;}@Overridepublic User getModel() {return user;}}


在 src 下新建 xwork-conversion.properties

待转换的类型=类型转换器的全类名

java.util.Date=cn.cil.conversion.DateConversion

PS:在当前 Struts2 应用被加载时创建实例


覆盖默认的错误消息:

1). 在对应的 Action 类所在的包中新建  
   ActionClassName.properties 文件, ActionClassName 即为包含着输入字段的 Action 类的类名
2). 在属性文件中添加如下键值对: invalid.fieldvalue.fieldName=xxx

UserAction.properties

invalid.fieldvalue.birth=\u8BF7\u8F93\u5165\u6B63\u786E\u7684\u751F\u65E5


0 0
原创粉丝点击