public class User {
private String name;
private Date birthday;
//getter and setter...
}
public class IndexAction2 extends ActionSupport{
//private Date date;
private User u;
public User getU() {
return u;
}
public void setU(User u) {
this.u = u;
}
public String userAdd(){
HttpServletRequest request = ServletActionContext.getRequest();
String birStr=request.getParameter("birthday");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
u.setBirthday(sdf.parse(birStr));
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(u.getBirthday());
return "suc";
}
public String userAdd1(){
System.out.println("date::"+date);
u.setBirthday(date);
System.out.println(u.getBirthday());
return "suc";
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
jsp:
<form action="path/path!userAdd1.action" name="myform" method="post">
姓名:<input type="text" name="u.name"><br>
生日:<input type="text" name="date">eg: 1986-06-15 00:00:00<br>
<a href="path/path.action">路径问题说明</a><br>
<button type="submit">OK</button><br>
</form>
若在jsp中想把表单的值直接传给对应的实体类,如果存在事件类型,那么u.birthday传入的值会出错,报类型转换异常。struts2的类型转换机制,只是可以把表单的值转换为对应的action中定义的属性,如action中定义private Date date;在表单上填入日期的时候用input type="text" name="date">,这样就可以自动转换。
如果不定义属性,想直接用实体类接收,那必须自己用SimpleDateFormat转换setbirthday()就好了。