Strust2里面的类型转换一般是自动完成的。但有时候需要自己定义类型的转换,比如将(x,y)转换为point类型之类。转换方式如下
一、建立转换器
将输入的 “aa,bb” 转换为user对象,用户名、密码。(这个例子有点弱智,如果真的是User,应该不这么用,直接用OGNL了事。)
public class UserConvert extends DefaultTypeConverter { @Override public Object convertValue(Map context, Object value, Class toType) { // TODO Auto-generated method stub //从字符串类型转换为复合类型 if (toType==User.class) { String [] params =(String[])value; User user = new User(); String [] userValues = params[0].split(","); user.setName(userValues[0]); user.setPassword(userValues[1]); System.out.println("i am in vonvert。。。。。"); return user; }else if(toType ==String.class) { User user =(User)value; return "<"+ user.getName()+","+user.getPassword()+">"; } return null; } }
二、在Action中使用
public class LogonAction extends ActionSupport { private String msg; private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String execute() { // TODO Auto-generated method stub msg =user.getName()+","+user.getPassword(); return SUCCESS; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
三、设置资源文件
actionname-coversion.properties,如:LogonAction-coversion.properties,和action放在同一地方
user=com.meetcomet.util.UserConvert
如果要设置全局的转换器,放在在src下,文件为xwork-conversion.properties
com.meetcomet.vo.User=com.meetcomet.util.UserConvert
要换成类名。
四、JSP
1)提交的login.jsp
<s:form action="/user/login" method="post" > <s:textfield name="user" label="登录"/> <s:submit value="确定"/> </s:form>
2)success页面
<s:property value="msg"/>