我们已经知道,Struts2的Action类里可以包含多个处理逻辑,不同的处理逻辑对应不同的方法。即Struts2的Action类里定义了几个类似于execute的方法,只是方法名不是execute。
如果我们的输入校验只想校验某个处理逻辑,也就是仅仅校验某个处理方法,则重写validate方法显然不合适,因为如果重写validate的话,那么无论调用Action的哪个方法,都会触发校验,这显然不是我们所希望看到的。此时的解决办法就是:如果要仅仅校验xxx方法,那么就重写validateXxx方法。
index.jsp :
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Insert title here</title>
<script type="text/javascript">
function login(){
var targetForm=document.forms[0];
targetForm.action="login_Action";
}
function register(){
var targetForm=document.forms[0];
targetForm.action="register_Action";
}
</script>
</head>
<body>
<s:actionerror/>
<s:fielderror></s:fielderror>
<s:form action="login_and_register">
<s:textfield name="name" label="姓名"></s:textfield>
<s:password name="pass" label="密码" showPassword="true"></s:password>
<s:submit value="注册" οnclick="register();"></s:submit>
<s:submit value="登录" οnclick="login();"></s:submit>
</s:form>
</body>
</html>
welcome.jsp :
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
welcome ${name}...
</body>
</html>
struts.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<package name="demo" extends="struts-default">
<action name="*_Action" class="action.RegisterAndLoginAction" method="{1}">
<result name="register_success">/index.jsp</result>
<result name="login_success">/welcome.jsp</result>
<result name="input">/index.jsp</result>
<result name="error">/index.jsp</result>
</action>
</package>
</struts>
RegisterAndLoginAction.java :
public class RegisterAndLoginAction extends ActionSupport {
private String name;
private String pass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public void validateRegister(){
System.out.println("进入到validateRegister()方法...");
if(name.equals("")||name==null){
this.addFieldError("name1","姓名不能为空");
}
if(name.length()<3||name.length()>25){
this.addFieldError("name2","英文姓名长度不能小于3也不能大于25");
}
if(pass.equals("")||pass==null){
this.addFieldError("pass1","密码不能为空");
}
if(pass.length()<3||pass.length()>25){
this.addFieldError("pass2","密码长度不能小于3也不能大于25");
}
}
public String login(){
if(name.equals("scott")&& pass.equals("tiger")){
ActionContext.getContext().getSession().put("name",name);
return "login_success";
}
this.addActionError("用户名或密码不正确");
return "error";
}
public String register(){
if(name.equals("scott")&& pass.equals("tiger")){
return "register_success";
}
return "error";
}
}