页面输入data类型字符串 转换成data类型
jsp页面
<s:form action="conversion"> <s:textfield name="age" label="Age"></s:textfield> <s:textfield name="birth" label="Birth"></s:textfield> <s:submit></s:submit> </s:form>
converter 转换所有Data类型
package com.converters; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import javax.servlet.ServletContext; import org.apache.struts2.ServletActionContext; import org.apache.struts2.util.StrutsTypeConverter; public class DateConverter extends StrutsTypeConverter { private DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); public DateConverter() { //System.out.println("DateConverter's constructor..."); } @Override public Object convertFromString(Map context, String[] values, Class toClass) { //System.out.println("convertFromString..."); if(toClass == Date.class){ if(values != null && values.length > 0){//String转换成Data String value = values[0]; //System.out.println(value); try { return dateFormat.parseObject(value); } catch (ParseException e) { e.printStackTrace(); } } } //若没有转换成功, 则返回 values return values; } @Override public String convertToString(Map context, Object o) {//Data转换成String到页面 System.out.println("convertToString..."); if(o instanceof Date){ Date date = (Date) o; return dateFormat.format(date); } //若转换失败返回 null return null; } }
在src目录下配置xwork-conversion.properties文件其中内容
java.util.Date=com.converters.DateConverter
Student类
package com.converters; import java.util.Date; public class Student { private int age; public void setAge(int age) { this.age = age; } public int getAge() { return age; } private Date birth;//Data型 public void setBirth(Date birth) { this.birth = birth; } public Date getBirth() { return birth; } @Override public String toString() { return "Student [age=" + age + ", birth=" + birth + "]"; } }
ConversionAction
package com.converters; import java.util.Date; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; public class ConversionAction extends ActionSupport implements ModelDriven<Student>{ /** * */ private static final long serialVersionUID = 1L; public String execute(){ System.out.println("Student: " + stu); return "success"; } private Student stu; @Override public Student getModel() { stu = new Student(); return stu; } }
运行结果