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"; }}struts2.xml:
date.jsp:/date.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>Insert title here ${time }
代码如上,假设在地址栏输入:
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然后在DateAction所在包下创建DateAction-conversion.properties文件。这里DateAction为所要进行參数类型转换的action,其它格式固定,即:XXX-conversion.propertiescontext, 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项目树:
====================================================================================================
以上的是针对某一个action的局部类型转换器。
也能够创建全局类型转换器,这里仅仅须要改动资源文件:
在WEB-INF/classes文件夹下创建xwork-conversion.properties,在该文件里配置的内容为:
待转换的类型=类型转换期的全类名
本例:
java.util.Date=com.itheima.type.converter.DateTypeConverter这样全部的action都会拥有该类型转换器