Struts2表单请求流程(二)— Struts2高级的POJO访问
时间:2011-09-24
Struts 2.0支持更高级的POJO访问,先定义一个User.java类。把username和password属性,从Login类中分离出来,它可以使系统结构更清晰,对开发多层系统尤其有用。
User.java
package com.bulktree.struts2;
public class User {
private String username;
private String password;
public String getUsername() {
System.out.println("******getUsername()******");
return username;
}
public void setUsername(String username) {
System.out.println("*******setUsername()********");
this.username = username;
}
public String getPassword() {
System.out.println("******getPassword()*******");
return password;
}
public void setPassword(String password) {
System.out.println("******setPassword()*********");
this.password = password;
}
}
login2.jsp
<s:form action="login2" method="post">
<s:textfield name="user.username" label="USERNAME" tooltip="Enter Your UserName"></s:textfield>
<s:password name= "user.password" label="PASSWORD" tooltip="Enter Your PassWord"></s:password>
<s:submit label="login"></s:submit>
</s:form>struts.xml文件中action配置:
<action name="login2" class="com.bulktree.struts2.LoginAction2">
<result name="success">/welcome.jsp</result>
<result name="input">/login2.jsp</result>
</action>
LoginAction2.java:
package com.bulktree.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction2 extends ActionSupport {
private User user;
private String message;
public void setUser(User user) {
System.out.println("********setUser()***********");
this.user = user;
}
public User getUser() {
System.out.println("*********getUser()*************");
return user;
}
public String getMessage() {
System.out.println("************getMessage()********");
return message;
}
@Override
public String execute() throws Exception {
System.out.println("*****execute()******");
if("bulktree".equals(user.getUsername()) && "oakertree".equals(user.getPassword())) {
message = "Welcome, " + user.getUsername();
} else {
message = "Error!";
}
return ActionSupport.SUCCESS;
}
@Override
public void validate() {
System.out.println("******validate()******");
if(null == user.getUsername() || user.getUsername().length() < 5) {
this.addFieldError("username","USERNAME ERROR");
}
if(null =
|