实体bean的
package com.bean;
public class User {
private :arrow: 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;
}
}
struts2.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/main" extends="struts-default">
<action name="struts2Index_*" class="com.struts2.action.Struts2ConverterAction" method="{1}" >
<result type="dispatcher">
/index.jsp
</result>
</action>
</package>
</struts>
控制器actin
package com.struts2.action;
import org.apache.log4j.Logger;
import com.bean.User;
public class Struts2ConverterAction {
private static Logger logger = Logger.getLogger(Struts2ConverterAction.class);
private User user;
public String loginUser(){
System.out.println(user.getUsername() + ":" + user.getPassword());
return "success";
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
注册器
package com.struts2.strutsconverter;
import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;
import com.bean.User;
public class Struts2Converter extends StrutsTypeConverter {
@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
User user = new User();
String[] strValue = values[0].split(",");
user.setUsername(strValue[0]);
user.setPassword(strValue[1]);
return user;
}
@Override
public String convertToString(Map context, Object o) {
User user = (User)o;
return user.getUsername() + "," + user.getPassword();
}
}
试图jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<form action="/StrutsTypeConverter/main/struts2Index_loginUser" method="post">
<input type="text" name="user" value="${user.username },${user.password }" />
<input type="submit" value="提交" />
</form>
</body>
</html>
最后配置注册器,在classpath目录下配置如下配置文件,文件名为固定格式:
xwork-conversion.properties
具体配置为:
com.bean.User=com.struts2.strutsconverter.Struts2Converter