package com.zchen.struts.action;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
private static final long serialVersionUID = 5497987645500599609L;
private 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;
}
public String execute() throws Exception {
if("hello".equals(this.getUsername().trim()) && "world".equals(this.getPassword().trim())){
return "success";
}else{
this.addFieldError("username", "username or password error!");
return "failer";
}
}
@Override
public void validate() {
if(null == this.getUsername() || "".equals(this.getUsername().trim())){
this.addFieldError("username", "username required");
}
if(null == this.getPassword() || "".equals(this.getPassword().trim())){
this.addFieldError("password", "password required");
}
}
}
<?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.devMode" value="true" /> <package name="login" extends="struts-default" > <action name="login" class="com.zchen.struts.action.UserAction"> <result name="success">/result.jsp</result> <result name="input">/login.jsp</result> <result name="failer">/login.jsp</result> </action> </package> </struts>
<body> <s:form method="post" action="login.action"> <s:textfield label="Username" name="username" /> <s:textfield label="Password" name="password" /> <s:submit /> </s:form> </body>
<body> username:<%=request.getParameter("username") %><br> password:<%=request.getParameter("password") %><br> </body>
注:struts先运行validate()方法再加载execute()方法