User类(将前台传来的字符串要转化的类,即一个pojo类)
package com.hcj.model; public class User { public String username; public String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public User() { super(); } }前台代码:
<%@ 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> <h1>用户类型转换器,用户名和密码间用英文逗号隔开</h1> <form action="testManyUserAction!test.action" method="post"> 请输入用户信息<input type="text" name="user"> 请输入客人信息<input type="text" name="user"> <input type="submit" value="提交"> </form> </body> </html>
package com.hcj.typeConvent; import java.util.Map; import org.apache.struts2.util.StrutsTypeConverter; import com.hcj.model.User; //自定义类型转换器类要实现TypeConverter借口,这里继承实现该接口的StrutsTypeConverter public class MyTypeConvent2 extends StrutsTypeConverter{ @Override //处理将字符串类型转换成复合类型的方法 public Object convertFromString(Map context, String[] values, Class toClass) { //如果请求参数数组的长度大于1 if(values.length > 1){ //创建一个User实例 User[] result = new User[values.length]; //遍历请求参数数组 for (int i = 0; i < result.length; i++) { User user = new User(); String[] userValue = values[i].split(","); user.setUsername(userValue[0]); user.setPassword(userValue[1]); result[i] = user; } return result; }else{ //请求参数数组的长度为1 User user = new User(); String[] userValue = values[0].split(","); user.setUsername(userValue[0]); user.setPassword(userValue[1]); return user; } } @Override //处理把复合类型转换成字符串类型的方法 public String convertToString(Map context, Object o) { //如果需要转换的值为单个的User实例 if(o instanceof User){ User user = (User)o; return "<" + user.getUsername() + "," + user.getPassword() + ">"; } //如果需要转换的值是User数组 else if(o instanceof User[]){ User[] users = (User[])o; String result = "["; for(User user : users){ result += "<" + user.getUsername() + "," + user.getPassword() + ">"; } return result; } return ""; } }
#制定com.hcj.model.User的类型转换器为com.hcj.typeConvent.MyTypeConvent.MyTypeConvent2 com.hcj.model.User=com.hcj.typeConvent.MyTypeConvent2
原文地址:http://blog.csdn.net/u011768325/article/details/45310381