我们通过表单输入的数据其实都是一个String,有时需要把这些String转成int date等等
Struts1中也提供了类型转换器,比如form中有一个字段age,当我们输入表单时, Struts1的转换器会将这个age字符串转换成Form表单中对应的age数值,Struts2提供了更加强大的类型转换.
实例:
提供一个文本框,输入用户名和密码,以”,”号分隔开
首先新建输入页面(input.jsp)
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<s:form action="userAction.action">
<s:textfield name="user" label="username and password"></s:textfield>
</s:form>
</body>
</html>
创建一个用户pojo(User.java)
package com.bean; public class User { private String username; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
然后增加自定义转换器 (UserConverter.java)
package com.converter; import java.util.Map; import com.bean.User; import ognl.DefaultTypeConverter; public class UserConverter extends DefaultTypeConverter { @Override public Object convertValue(Map content, Object value, Class typeClass) { if(String.class == typeClass){ User user = (User)value; String username = user.getUsername(); String password = user.getPassword(); return username + "-" + password; } if(User.class == typeClass){ User user = new User(); String[] str = (String[])value; String[] paramValues = str[0].split(","); user.setUsername(paramValues[0]); user.setPassword(paramValues[1]); return user; } return null; } }
创建Action (UserAction.java)
package com.action; import com.bean.User; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport { private static final long serialVersionUID = 8469145731747703330L; private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String execute() throws Exception { if("callan".equals(user.getUsername()) && "fjf".equals(user.getPassword())){ return SUCCESS; } else { return INPUT; } } }
添加struts.xml中添加以下配置
<action name="userAction" class="com.action.UserAction"> <result name="success">/welcome.jsp</result> <result name="input">/input.jsp</result> </action>
接着在Action同目录下加入XXX-conversion.properties
这里是在UserAction目录下加入UserAction-conversion.properties,并在其中加入
user=com.converter.UserConverter
user表示的是UaerAction中的一个字段,user使用com.converter.UserConverter转换器
也可以配置全局转换器,在class根目录下添加xwork-conversion.properties,这个名字是固定的,加入com.bean.User=com.converter.UserConverter2表示所有的com.bean.User都使用的是UserConverter2转换器