自己定义struts2中action类型转换器

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:

<action name="dateAction" class="com.itheima.action.DateAction">
	<result name="success">/date.jsp</result>
</action>

date.jsp:

<%@ 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所在包下创建DateAction-conversion.properties文件。这里DateAction为所要进行參数类型转换的action,其它格式固定,即:XXX-conversion.properties

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都会拥有该类型转换器

原文地址:https://www.cnblogs.com/claireyuancy/p/7190706.html