06.Struts2中的拦截器及类型转换

06.Struts2中的拦截器及类型转换

1、什么是拦截器

拦截器(Interceptor):

拦截器是Struts2的核心,Struts2的众多功能都是通过拦截器来实现的。

2、拦截器的作用

作用:拦截用户的请求,对请求进行一些预处理,当请求完毕之后,又可以对请求进行后续的处理,对相应进行后续的处理。作用和过滤器很类似。

3、 拦截器的配置

1)编写实现Interceptor 接口的类。
2)在struts.xml文件里定义拦截器。
3)在action中使用拦截器 。

<!-- 让该package使用其中定义的拦截器栈 -->
<interceptors>
    <!-- 拦截器栈名 -->
    <interceptor-stack name="myInterceptor"><!--name:见名知意-->
        <!-- 引用预先调用pramas的拦截器栈 -->
        <interceptor-ref name="paramsPrepareParamsStack">
            <param name="prepare.alwaysInvokePrepare">false</param>
        </interceptor-ref>
    </interceptor-stack>
</interceptors>
<default-interceptor-ref name="myInterceptor"></default-interceptor-ref>

在程序中的使用如下:

action动态的添加

输入验证(验证用户输入的是否正确)

对象组装(将用户输入的数据转换为对象的属性)

权限控制(如访问者为登录用户)

日志记录(记录action的执行情况)

这些操作都可以通过拦截器实现,而不用修改action

4、拦截器的工作流程

Action命令(执行)–>拦截器1–>拦截器2–>拦截器n–>Action–>拦截器1–>拦截器2–>拦截器n(返回)–>Action命令

5、自定义类型转换器

概述:在Struts2中,支持全局类型转换和局部类型转换两种方式。所谓全局类型转换,即在所有的action/model中,都用同一个类型转换器来转换某种特定类型的对象;而局部类型转换,意思就是针对某个action/model中的属性所定义的特定的类型转换器。

1)全局类型转换

  • 即针对整个系统中同样类型的属性定义转换器

    只需:

    1、 在类路径的根目录下定义xwork-conversion.properties文件(命名必须一致)

    2、 在文件中用这样的格式声明哪个类型使用哪个转换器:

    ​ 属性类型的全路径类名=转换器的全路径类名

    3、 Struts2将能自动发现这个文件,并根据其中的定义,对特定的类型调用你指定的类型转换器进行类型转换

案例1:

Point类型

package cn.com.leadfar.model;
public class Point {

    private int left;

    private int right;

    public int getLeft() {

       return left;

    }

    public void setLeft(int left) {

       this.left = left;

    }

    public int getRight() {

       return right;

    }

    public void setRight(int right) {

       this.right = right;

    }
}

Point类型的转换器

package cn.com.leadfar.struts2.actions;
import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;
import cn.com.leadfar.model.Point;

public class PointConverter extends StrutsTypeConverter {

    @Override

    public Object convertFromString(Map context, String[] value, Class toType) {

       //TODO 前提条件判断
       String p = value[0];

       String[] ps = p.split(",");

       int left = Integer.parseInt(ps[0]);

       int right = Integer.parseInt(ps[1]);

       Point point = new Point();

       point.setLeft(left);

       point.setRight(right);

       return point;
    }

    @Override

    public String convertToString(Map context, Object point) {

       Point p = (Point)point;

       return p.getLeft()+"-"+p.getRight();

    }
}

xwork-conversion.properties文件的内容如下:

<!--属性类型的全路径类名=转换器的全路径类名-->
cn.com.leadfar.model.Point=cn.com.leadfar.struts2.actions.PointConverter

2)局部类型转换

即针对某个ActionModel的属性定义的转换器

1、在与Action/Model类同一个包下面,定义 Action/Model类名-conversion.properties文件

2、文件内部用这样的格式来声明哪个属性需要用哪个类型转换器:

属性名*=*转换器的全路径类名

案例2:

java.util.Date类型,可以声明不同的类使用不同的类型转换器

package cn.com.leadfar.model;
import java.util.Date;

public class User {

    private Date endDate;

    public Date getEndDate() {

       return endDate;

    }

    public void setEndDate(Date endDate) {

       this.endDate = endDate;

    }
}
package cn.com.leadfar.struts2.actions;

 

import java.util.Date;

 

import cn.com.leadfar.model.Point;

import cn.com.leadfar.model.User;

 

import com.opensymphony.xwork2.ModelDriven;

 

 

public class UserAction implements ModelDriven{

    private User user;
    private Date beginDate;

    @Override

    public Object getModel() {
       if(user == null){
           user = new User();
       }
       return user;
    }

    public String add(){
       return "success";
    }

    public User getUser() {
       return user;
    }

    public void setUser(User user) {

       this.user = user;

    }

    public Date getBeginDate() {

       return beginDate;

    }

    public void setBeginDate(Date beginDate) {

       this.beginDate = beginDate;

    }
}

例如:UserAction类中的beginDate属性和User类中endDate属性,分别使用不同的类型转换器

package cn.com.leadfar.struts2.actions;

 

import java.text.ParseException;

import java.text.SimpleDateFormat;
import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;

public class BeginDateConverter extends StrutsTypeConverter {

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Object convertFromString(Map context, String[] value, Class toType) {

       String d = value[0];
       try {

           return format.parse(d);

       } catch (ParseException e) {
           e.printStackTrace();
       }

       return null;

    }

    @Override
    public String convertToString(Map context, Object date) {

       return format.format(date);
    }
}
package cn.com.leadfar.struts2.actions;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;

public class EndDateConverter extends StrutsTypeConverter {

    private SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

    @Override
    public Object convertFromString(Map context, String[] value, Class toType) {

       String d = value[0];
       try {
           return format.parse(d);
       } catch (ParseException e) {
           e.printStackTrace();
       }
       return null;
    }

    @Override
    public String convertToString(Map context, Object date) {

       return format.format(date);

    }
}

我们需要在User类的包:cn.com.leadfar.model下面,创建一个文件

User-conversion.properties,文件的内容如下:

<!--属性名*=*转换器的全路径类名-->
endDate=cn.com.leadfar.struts2.actions.EndDateConverter

表示User类中的endDate属性,使用EndDateConverter这个类型转换器。

然后,在UserAction类所在的包:cn.com.leadfar.struts2.actions下面,再创建一个文件,命名如下:

UserAction-conversion.properties,文件的内容如下:

beginDate=cn.com.leadfar.struts2.actions.BeginDateConverter

表示UserAction类中的beginDate属性,使用BeginDateConveter这个类型转换器。

注意,在Struts1中只支持全局类型转换,而不支持局部类型转换!

3)如何自定义类型转换器

a、创建类作为转换器类

b、继承Struts2的转换器

​ 继承StrutsTypeConverter

c、重写方法

​ convertFromString:从字符串转为目标数据类型

​ convertToString:目标数据类型转换为字符串

d、配置自定义转换器

​ 基于类型配置

​ 在src目录下创建xwork-conversion.properties属性文件

​ 目标数据类型全类名=转换器类的全类名

​ 基于字段的配置

​ 在字段所属的类的同包目录下创建 类名-conversion.properties属性文件

​ 属性名=转换器类的全类名

6、上课代码(案例)

导入相应的jar

06.Struts2中的拦截器及类型转换

jsp页面

page01.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<s:form method="POST" action="user/insertUserInfo">
		<s:textfield name="userName" label="userName"></s:textfield>
		<s:textfield name="userAge" label="userAge"></s:textfield>
		<s:textfield name="userSex" label="userSex"></s:textfield>
		<s:textfield name="userEmail" label="userEmail"></s:textfield>
		<s:textfield name="userAddress" label="userAddress"></s:textfield>
		<s:submit value="注册"></s:submit>
	</s:form>
	<hr/>
	<s:form method="POST" action="user/deleteUserInfoById">
		<s:textfield name="id" label="id"></s:textfield>
		<s:submit value="注册"></s:submit>
	</s:form>
</body>
</html>

page02.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<s:form method="POST" action="user2/insertUserInfo">
		<s:textfield name="userName" label="userName"></s:textfield>
		<s:textfield name="userAge" label="userAge"></s:textfield>
		<s:textfield name="registerTime" label="registerTime"></s:textfield>
		<s:submit value="注册"></s:submit>
	</s:form>
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>操作成功!</h1>
	<s:debug></s:debug>
</body>
</html>

fieldError.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>属性转换出错了!</h1>
	<s:debug></s:debug><br/>
	<s:property value="fieldErrors"/>
	<s:fielderror></s:fielderror>
</body>
</html>

配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>strutsTest07</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<filter>
		<filter-name>dispatcherFilter</filter-name>
		<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>dispatcherFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

配置struts2.xml文件(必须放在src目录下)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<constant name="struts.action.extension" value="do,test,action,,"></constant>
	<constant name="struts.devMode" value="true"></constant>
	
	<package name="user" extends="struts-default" namespace="/user">
		<!-- 让该package使用其中定义的拦截器栈 -->
		<interceptors>
			<!-- 拦截器栈名 -->
			<interceptor-stack name="myInterceptor">
				<!-- 引用预先调用pramas的拦截器栈 -->
				<interceptor-ref name="paramsPrepareParamsStack">
					<param name="prepare.alwaysInvokePrepare">false</param>
				</interceptor-ref>
			</interceptor-stack>
		</interceptors>
		<default-interceptor-ref name="myInterceptor"></default-interceptor-ref>
		<action name="deleteUserInfoById" class="com.zb.action.UserAction" method="deleteUserInfoById">
			<result>/success.jsp</result>
		</action>
		<action name="insertUserInfo" class="com.zb.action.UserAction" method="insertUserInfo">
			<result>/success.jsp</result>
		</action>
	</package>	
	
	<package name="user2" extends="struts-default" namespace="/user2">
		<action name="insertUserInfo" class="com.zb.action.UserAction02" method="insertUserInfo">
			<result name="success">/success.jsp</result>
			<result name="input">/fieldError.jsp</result>
		</action>
	</package>	
</struts>

配置xwork-conversion.properties(全局类型转换必须放在src目录下)

<!--属性类型的全路径类名=*转换器的全路径类名*-->
java.util.Date=com.zb.comverter.MyString2DateConverter

Action类

package com.zb.action;

import java.sql.SQLException;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.zb.dao.UserDao;
import com.zb.entity.UserInfo;

public class UserAction implements ModelDriven<UserInfo>,Preparable {

	private UserInfo userInfo;
	private Integer id;
	
	
	public String deleteUserInfoById() {
		
		System.out.println("删除");
		
		System.out.println(id);
		
		return "success";
	}

	public String insertUserInfo() {
		
		// System.out.println("执行添加操作");
		//System.out.println(this.userInfo);
		UserDao ud = new UserDao();
		
		try {
			ud.insertUserInfo(this.userInfo);
		} catch (SQLException e) {
			System.out.println("添加用户失败");
		}
		
		return "success";
	}
	
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}
	
	//Preparable
	@Override
	public void prepare() throws Exception {
		System.out.println("prepare方法执行了");
	}
	
	public void prepareDeleteUserInfoById() {
		System.out.println("deleteUserInfoById方法的前缀方法执行了");
	}
	
	public void prepareInsertUserInfo() {
		System.out.println("insertUserInfo方法的前缀方法执行了");
		userInfo = new UserInfo();
	}
	
	@Override
	public UserInfo getModel() {
		System.out.println("getModel执行了");
		return userInfo;
	}
}
package com.zb.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.zb.entity.UserInfo;

public class UserAction02 extends ActionSupport implements ModelDriven<UserInfo>{
	
	private UserInfo userInfo;
	
	/**
	 * 	Struts中的类型转换
	 * 		1、Struts已经提供了大量,几乎所有的类型转换器,不需要我自己在意
	 * @return
	 */
	
	public String insertUserInfo() {
		
		System.out.println("Action02insertUserInfo");
		
		System.out.println(userInfo);
		
		return "success";
	}
	
	@Override
	public UserInfo getModel() {
		userInfo = new UserInfo();
		return userInfo;
	}
	
}

UserAction02.properties文件(必须放在对应的Action类/model中)

<!--invalid.fieldvalue(固定值).属性名-->
invalid.fieldvalue.userAge=zhi neng shi shuzi a
invalid.fieldvalue.registerTime=\u5FC5\u987B\u662Fyyyy-MM-dd\u683C\u5F0F

common类(数据库工具类)

package com.zb.common;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBUtil {
	private static ComboPooledDataSource dataSource;
	
	static {
		dataSource = new ComboPooledDataSource();
		
		try {
			dataSource.setDriverClass("com.mysql.jdbc.Driver");
			dataSource.setJdbcUrl("jdbc:mysql:///user_db?characterEncoding=UTF-8");
			dataSource.setUser("root");
			dataSource.setPassword("123456");
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
		
	}
	
	public static Connection getConnection() {
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void disConnect(Connection conn) {
		try {
			if(conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

comverter(类型转换类)

package com.zb.comverter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

/**
 * 	自定义类型转换器
 * 		1、创建类作为转换器类
 * 		2、继承Struts2的转换器
 * 			StrutsTypeConverter
 * 		3、重写方法
 * 			convertFromString:从字符串转为目标数据类型
 * 			convertToString:目标数据类型转换为字符串
 * 		4、配置自定义转换器
 * 			基于类型配置
 * 				在src目录下创建xwork-conversion.properties属性文件
 * 					目标数据类型全类名=转换器类的全类名
 *			基于字段的配置
 *				在字段所属的类的同包目录下创建 类名-conversion.properties属性文件
 *					属性名=转换器类的全类名
 * @author Administrator
 *
 */
public class MyString2DateConverter extends StrutsTypeConverter {

	/**
	 * context:值栈的context
	 * values:被转换的数据放在该数组中
	 * toClass:转换的目标数据类型
	 * 	@return:转换后的结果需要返回回去,交给params拦截器将该转换结果设置到指定的属性中
	 */
	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		
		System.out.println("被转换的字符串:"+values[0]);
		System.out.println("转换成的目标类型:"+toClass);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		Date dt=null;
		try {
			dt = sdf.parse(values[0]);
		} catch (ParseException e) {
			System.out.println("自定义转换异常");
			e.printStackTrace();
		}
		return dt;
	}

	@Override
	public String convertToString(Map context, Object o) {
		return null;
	}
}

dao类

package com.zb.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.zb.common.DBUtil;
import com.zb.entity.UserInfo;

/**
 * 用户信息DAO类
 * @author Java53
 *
 */
public class UserDao {

	/**
	 * 分页查询用户信息
	 * @param pageNo 页码
	 * @return 用户信息集合
	 * @throws SQLException
	 */
	public List<UserInfo> selectUserInfoByPager(int pageNo) throws SQLException {
		Connection conn = DBUtil.getConnection();
		PreparedStatement pst = conn.prepareStatement(" SELECT * FROM user_info LIMIT " + ((pageNo - 1) * 3) + ",3 ");
		ResultSet res = pst.executeQuery();
		List<UserInfo> listUserInfo = new ArrayList<UserInfo>();
		while (res.next()) {
			UserInfo userInfo = new UserInfo(
					res.getInt(1), 
					res.getString(2), 
					res.getInt(3), 
					res.getString(4),
					res.getString(5), 
					res.getString(6), 
					res.getDate(7));
			listUserInfo.add(userInfo);
		}
		DBUtil.disConnect(conn);
		return listUserInfo;
	}
	
	public boolean insertUserInfo(UserInfo userInfo) throws SQLException {
		Connection conn = DBUtil.getConnection();
		PreparedStatement pst = conn.prepareStatement(" INSERT INTO user_info VALUES(DEFAULT,?,?,?,?,?,NOW()) ");
		pst.setString(1, userInfo.getUserName());
		pst.setInt(2, userInfo.getUserAge());
		pst.setString(3, userInfo.getUserSex());
		pst.setString(4, userInfo.getUserEmail());
		pst.setString(5, userInfo.getUserAddress());
		return pst.executeUpdate()>0?true:false;
	}
}

entity(实体类)

package com.zb.entity;

import java.util.Date;

/**
 * 用户信息实体类
 * @author Java53
 *
 */
public class UserInfo {
	private Integer id;
	private String userName;
	private Integer userAge;
	private String userSex;
	private String userEmail;
	private String userAddress;
	private Date registerTime;

	public UserInfo() {
		super();
	}

	public UserInfo(Integer id, String userName, Integer userAge, String userSex, String userEmail, String userAddress,
			Date registerTime) {
		super();
		this.id = id;
		this.userName = userName;
		this.userAge = userAge;
		this.userSex = userSex;
		this.userEmail = userEmail;
		this.userAddress = userAddress;
		this.registerTime = registerTime;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public Integer getUserAge() {
		return userAge;
	}

	public void setUserAge(Integer userAge) {
		this.userAge = userAge;
	}

	public String getUserSex() {
		return userSex;
	}

	public void setUserSex(String userSex) {
		this.userSex = userSex;
	}

	public String getUserEmail() {
		return userEmail;
	}

	public void setUserEmail(String userEmail) {
		this.userEmail = userEmail;
	}

	public String getUserAddress() {
		return userAddress;
	}

	public void setUserAddress(String userAddress) {
		this.userAddress = userAddress;
	}

	public Date getRegisterTime() {
		return registerTime;
	}

	public void setRegisterTime(Date registerTime) {
		this.registerTime = registerTime;
	}

	@Override
	public String toString() {
		return "UserInfo [id=" + id + ", userName=" + userName + ", userAge=" + userAge + ", userSex=" + userSex
				+ ", userEmail=" + userEmail + ", userAddress=" + userAddress + ", registerTime=" + registerTime + "]";
	}

}

配置UserInfo-conversion.properties文件

registerTime=com.zb.comverter.MyString2DateConverter

7、练习

1、通过前置方法完成:当请求方法为注册方法时,向值栈中加入用户对象
2、配置用户年龄错误提示为[年龄必须是整数值]
3、通过类型转换器,使用户输入的多张银行卡号能正确地存入卡号数组
input:123456,654321,456789,987654
String[] cardNumber:[123456,654321,456789,987654]
4、预习
A、Struts中的文件上传
B、Struts中的数据合法性验证
完成注册练习:
在用户注册页面上传用户头像
在用户注册页面上传身份证正反面照片
验证用户输入的年龄必须为18-30岁之间
用户输入的邮箱必须符合邮箱规则(包含@和.,@必须在.前面,)
用户输入的用户名不能为空

练习第三题评讲

导入相应的架包

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 action="user/showUserInfo">
		请输入银行卡号,以逗号分隔:<input type="text" name="userInfo"><br/>
		<input type="submit" value="提交">
	</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>欢迎!</h1>
<s:debug></s:debug>
</body>
</html>

配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>struts2Test08</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

	<filter>
		<filter-name>dispatcherFilter</filter-name>
		<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>dispatcherFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

配置struts.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<constant name="struts.action.extension" value="do,test,action,,"></constant>
	<constant name="struts.devMode" value="true"></constant>
	<!-- 允许静态方法调用 -->
	<constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>
	<package name="user" extends="struts-default" namespace="/user">
	<action name="showUserInfo" class="com.zb.entity.UserAction" method="showUserInfo">
		<result>/index.jsp</result>
	</action>
	</package>	
</struts>

配置xwork-conversion.properties文件(全局)

com.zb.entity.UserInfo=com.zb.converter.MyStringToUserInfoConverter

Action类

package com.zb.entity;

public class UserAction {
	private UserInfo userInfo;

	public String showUserInfo() {
		System.out.println(this.userInfo);
		
		return "success";
	}
	
	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}
}

converter(转换器)类

MyStringToUserInfoConverter.java

package com.zb.converter;

import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import com.zb.entity.UserInfo;

public class MyStringToUserInfoConverter extends StrutsTypeConverter {

	@Override
	public Object convertFromString(Map arg0, String[] arg1, Class arg2) {
		System.out.println("转换器在运转啦!");
		String[] strs = arg1[0].split(",");
		for(int i=0;i<strs.length;i++) {
			strs[i]="卡号:"+strs[i];
		}
		return new UserInfo(strs);
	}

	@Override
	public String convertToString(Map arg0, Object arg1) {
		// TODO Auto-generated method stub
		return null;
	}
}

entity类

package com.zb.entity;

import java.util.Arrays;

public class UserInfo {
	private String[] cardNumber;

	public String[] getCardNumber() {
		return cardNumber;
	}

	public void setCardNumber(String[] cardNumber) {
		this.cardNumber = cardNumber;
	}

	public UserInfo() {
		super();
	}

	public UserInfo(String[] cardNumber) {
		super();
		this.cardNumber = cardNumber;
	}

	@Override
	public String toString() {
		return "UserInfo [cardNumber=" + Arrays.toString(cardNumber) + "]";
	}

}

zb.converter;

import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import com.zb.entity.UserInfo;

public class MyStringToUserInfoConverter extends StrutsTypeConverter {

@Override
public Object convertFromString(Map arg0, String[] arg1, Class arg2) {
	System.out.println("转换器在运转啦!");
	String[] strs = arg1[0].split(",");
	for(int i=0;i<strs.length;i++) {
		strs[i]="卡号:"+strs[i];
	}
	return new UserInfo(strs);
}

@Override
public String convertToString(Map arg0, Object arg1) {
	// TODO Auto-generated method stub
	return null;
}

}


#### entity类

```java
package com.zb.entity;

import java.util.Arrays;

public class UserInfo {
	private String[] cardNumber;

	public String[] getCardNumber() {
		return cardNumber;
	}

	public void setCardNumber(String[] cardNumber) {
		this.cardNumber = cardNumber;
	}

	public UserInfo() {
		super();
	}

	public UserInfo(String[] cardNumber) {
		super();
		this.cardNumber = cardNumber;
	}

	@Override
	public String toString() {
		return "UserInfo [cardNumber=" + Arrays.toString(cardNumber) + "]";
	}

}
上一篇:Struts2请求参数接收


下一篇:【Struts2】Struts2框架访问Servlet API