在web的视图展现之中,所有的类型都表现为string类型,即“弱类型”,而在java世界里,所有的对象都表现为强类型,所以,一个框架必须解决字符串到java强数据类型的转化,而且2者必须可逆。
我们平时遇到的大部分基本类型的转化,struts2都能自动帮我们完成,但开发之中总免不了自定义格式的转化。
一.首先,来看看struts2对基本类型的转化:
测试实体:
package com.model; import java.util.Date; import com.zizhu.DateUtils; public class User { private int id ; private String name = null; private int age ; public char sex ; public double price; public float servicePrice; public char sex2; private Date birthday = null; public char getSex2() { return sex2; } public void setSex2(char sex2) { this.sex2 = sex2; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public float getServicePrice() { return servicePrice; } public void setServicePrice(float servicePrice) { this.servicePrice = servicePrice; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [age=" + age + ", birthday=" + DateUtils.format(birthday, "yyyy-MM-dd HH:mm:ss") + ", id=" + id + ", name=" + name + ", price=" + price + ", servicePrice=" + servicePrice + ", sex=" + sex + ", sex2="+sex2+"]"; } }
二.自定义类型的转化:
针对上面的Date类型,我们进行自定义格式来实现转化
第一步:定义一个转化的配置文件:xwork-conversion.properties
java.util.Date=com.utils.DateConvert第二步:指定这个实现类:
package com.utils; import java.util.Date; import java.util.Map; import org.apache.struts2.util.StrutsTypeConverter; public class DateConvert extends StrutsTypeConverter { @Override public Object convertFromString(Map context, String[] values, Class toClass) { if(values != null && values.length > 0){ return DateUtils.parse(values[0], "yyyy-MM-dd"); } return null; } @Override public String convertToString(Map context, Object o) { if(o instanceof Date){ return DateUtils.format((Date)o, "yyyy年MM月dd日"); } return null; } }
页面的输入代码:
<s:form action="hello"> <s:textfield label="姓名" name="user.name"></s:textfield> <s:textfield label="年龄" name="user.age"></s:textfield> <s:radio label="性别" list="@com.model.SexEnum@enmu2Coll()" name="user.sex"></s:radio> <s:textfield label="性别2" name="user.sex2"></s:textfield> <s:textfield label="出生日期" name="user.birthday"></s:textfield> <s:textfield label="价格" name="user.price"></s:textfield> <s:textfield label="服务费用" name="user.servicePrice"></s:textfield> <s:submit></s:submit> </s:form>
输出结果:User [age=1, birthday=2012-02-01 00:00:00, id=0, name=a, price=0.0, servicePrice=0.0, sex=男, sex2=女]