DateAction.java中代码如下:
package com.itheima.action;
import java.util.Date;
public class DateAction {
private Date time;
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String execute() {
return "success";
}
}
<action name="dateAction" class="com.itheima.action.DateAction"> <result name="success">/date.jsp</result> </action>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
${time }
</body>
</html>
代码如上,如果在地址栏输入:
http://localhost:8080/struts2_itheima/dateAction?time=2011-01-04
控制台和jsp都能够正常输出:
但是如果地址栏输入:
http://localhost:8080/struts2_itheima/dateAction?time=20110104
控制台输出null,网页则输出
这是因为此种输入方式,time参数传递的是String类型,调用setTime(Date time)方法出错,此时private Date time;获取到的值为空。
但是jsp能原样输出是因为struts2底层当setTime(Date time)方法出错时会自动获取参数的值原样输出
解决以上问题的方式是创建自定义类型转换器:
DateTypeConverter.java:
package com.itheima.type.converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
public class DateTypeConverter extends DefaultTypeConverter {
@Override
public Object convertValue(Map<String, Object> context, Object value,
Class toType) {
/*
value:被转换的数据,由于struts2需要接受所有的请求参数,比如复选框
toType:将要转换的类型
*/
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd");
if(toType == Date.class) {
/*
* 由于struts2需要接受所有的请求参数,比如复选框,这就导致一个参数名称对应多个值,
* 所以框架采用getParamterValues方法获取参数值,这就导致获取到的为字符串数组
* 所以value为字符串数组
*/
String[] strs = (String[])value;
Date time = null;
try {
time = dateFormat.parse(strs[0]);
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return time;
} else if(toType == String.class){
Date date = (Date)value;
String time = dateFormat.format(date);
return time;
}
return null;
}
}
DateAction-conversion.properties内容如下:
time=com.itheima.type.converter.DateTypeConverter项目树:
原文地址:http://blog.csdn.net/m631521383/article/details/40680723