借助于ognl表达式的支持,Struts2允许以一种简单方式将请求参数转换成复合类型。
LoginAction.java :
public class LoginAction extends ActionSupport{
private Person person;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public String execute(){
//some code
return "success";
}
}
Person.java :
public class Person {
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Person() {
super();
}
}
login.jsp :
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<s:form action="">
<s:textfield name="person.name" label="姓名"></s:textfield><br>
<s:password name="person.password" label="密码"></s:password>
<s:submit value="确定"></s:submit>
</s:form>
</body>
</html>
通过这种方式,Struts2可以将普通请求参数转换成复合类型对象,但在使用这种方式时有如下两点需要注意:
① 因为Struts2将通过反射来创建一个复合类(Person)的实例,因此必须为该复合类提供一个无参数的构造器
② 为复合类(Person)提供setter和getter方法。