struts2 自定义类型转换器(字符串到集合类型的转换)
前台有多个输入文本框(name均为users)每个输入框都按username,password的格式输入,提交后将请求参数封转为后台XXXAction的List<User>类型的属性,并在结果页面中打印此对象1.login.jsp
...
<s:form action="Login">
<s:textfield name="users" label="user1"></s:textfield><br />
<s:textfield name="users" label="user2"></s:textfield><br />
...
...
2.LoginAction.java
...
private List<User> users;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public String execute(){
return SUCCESS;
}
3.struts.xml配置LoginAction直接返回SUCCESS页面welcome.jsp
4.welcome.jsp
...
<s:property value="users" escape="false"/>
5.UserConverter.java
import...
public class UserConverter extends DefaultTypeConverter {
public Object convertValue(Map context,Object value,Class toType){
if(toType == List.class){
String[] params = (String[])value;
List<User> ll = new ArrayList<User>();
for(int i=0;i<params.length;i++){
String[] ss = params[i].split(",");
ll.add(new User(ss[0],ss[1]));
}
return ll;
}else if(toType == String.class){
String str="";
List users = (List)value;
for(Object u : users){
User user = (User)u;
str += "name: "+user.getName()+" pass:"+user.getPass()+"<br />";
}
return str;
}else{
return null;
}
}
}
6.LoginAction-conversion.properties与LoginAction在同一目录下
users=com.lg.app.converter.UserConverter
学生正在学习李刚的轻量级JavaEE,看书上例子练习了一下,希望和大家一起交流、学习!