struts2 自定义类型转换器 基础一案例

说明:此案例以用户以一个文本框的加","区分的方式输入用户名与密码,转换成User对象.

1. 先定义TblUser实体:

public class TblUser implements Cloneable {
 private String userName;
 private 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;
 }
}

 

2. 定义一个继承ognl.DefaultTypeConverter类的转换类,重写方法:convertValue

public class UserTypeConvert extends DefaultTypeConverter {
 @Override
 public Object convertValue(Map context, Object target, Member member,
   String propertyName, Object value, Class toType) {
  if (toType == TblUser.class) {
   String[] parame = (String[]) value;
   TblUser user = new TblUser();
   String[] userValues = parame[0].split(",");
   user.setUserName(userValues[0]);
   user.setPassWord(userValues[1]);
   return user;
  }
  if (toType == String.class) {
   TblUser user = (TblUser) value;
   return user.getUserName() + user.getPassWord();
  }
  return null;
 }
}

 

3. 注册使用.

局部注册:

于处理请求的action同目录新建一个properties文件匹配转换.

   如处理action名为:TypeConvertAction.

   文件名为:TypeConvertAction-conversion.properties

内容如下:

user=com.test.convert.UserTypeConvert

全局注册:

于WEB应用的WEB/INF/SRC下面新建一个properties文件.

名:xwork-conversion.properties.内容如上:

user=com.test.convert.UserTypeConvert

 

注意:

此user对象需要对应两个地方:

1. 处理action中的参数:

public class TypeConvertAction extends ActionSupport {

 private static final long serialVersionUID = 1450105477460242583L;

 private TblUser user;

 public TblUser getUser() {
  return user;
 }

 public void setUser(TblUser user) {
  this.user = user;
 }

 @Override
 public String execute() throws Exception {

  if (null == user) {
   return ERROR;
  }
  if (StringUtil.isNotNull(getUser().getUserName())) {
   System.out.println("转换成功:"+getUser().getUserName());
  }
  return SUCCESS;
 }
}

 

2. 请求页面的表单名:

 输入用户名和密码以,分开
  <s:form action="userManager/typeConvert.action">
        <s:textfield name="user" key="用户名和密码:"></s:textfield>
        <s:submit key="login"></s:submit>
  </s:form>

 

----------------------------完,开发经验,以供后续开发使用与交流.-------------------------------

---------------------------------------------------------------------------------------尹当

你可能感兴趣的:(Web)