Struts2默认能转换的时间书写方式是yyyy-MM-dd,想要转换其他类型的时间输入,就要利用到类型转换器。
首先要用一个Action类:
package com.hncj.edu;
import java.util.Date;
public class User {
private int age;
private Date birthday; //要转换的时间类型
private String name;
private String password;
public int getAge() {
return age;
}
public Date getBirthday() {
return birthday;
}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
public String loginUser() {
System.out.println(this.name);
System.out.println(this.age);
System.out.println(this.password);
System.out.println(this.birthday);
return "SUCCESS";
}
public void setAge(int age) {
this.age = age;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public void setName(String name) {
this.name = name;
}
public void setPassword(String password) {
this.password = password;
}
}
配置的类型转换器:
package com.hncj.converter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;
import com.opensymphony.xwork2.conversion.TypeConversionException;
public class DateConverter extends StrutsTypeConverter{
/*这是看网上一位朋友的代码,感觉写的不错,可以增添自己想要的时间输入形式*/
private final DateFormat[] dateFormat = {
new SimpleDateFormat("yyyy年MM月dd日"),
new SimpleDateFormat("yyyy-MM-dd"),
new SimpleDateFormat("yyyy.MM.dd"),
new SimpleDateFormat("yyyy/MM/dd"),
};
@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
String value = values[0];
//尝试所以能转换的类型
for(int i=0;i<dateFormat.length;i++) {
try {
return dateFormat[i].parse(value);
} catch (ParseException e) {
continue;
}
}
//没找到能转换的类型,抛出异常
throw new TypeConversionException();
}
@Override
public String convertToString(Map context, Object o) {
return new SimpleDateFormat("yyyy-MM-dd").format(o);
}
}
下面是配置转换器的文件,名字统一为xwork-conversion.properties,内容为:(必须放在src目录下)
java.util.Date=com.hncj.converter.DateConverter
上面是全局的配置方式,还可以用局部的配置方式,文件名为User-conversion.properties,位置放在User类所在的包下。
birthday=com.hncj.edu.DateConverter
jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/login">
<table>
<caption>用户登录</caption>
<tr>
<td>用户名:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age"/></td>
</tr>
<tr>
<td>生日:</td>
<td><input type="text" name="birthday"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>