(5)表单Action后台验证

/day31/src/cn/itcast/web/struts2/user/UserAction.java

package cn.itcast.web.struts2.user;

import com.opensymphony.xwork2.ActionContext;

public class UserAction {
        //表单参数
        private String username;
        private String password;
        //提供对应的setter方法(拦截器会将表单参数通过setter方法自动注入进来)
        public void setUsername(String username) {
            this.username = username;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        //注册的业务控制方法 
        public String registerMethod(){
            System.out.println("用户名:" + username);
            System.out.println("密码:" + password);
            //将用户名和密码绑定到域对象
            ActionContext.getContext().put("username",username);
            ActionContext.getContext().put("password",password);
            return "success";
        }
}

/day31/WebRoot/register.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <script type="text/javascript" src="js/jquery-1.8.2.js"></script>
    <script type="text/javascript" >
        $(function(){
            $("form").submit(function(){
                var flag=false;
                var username=$(":text:first").val();
                var password=$(":text:last").val();
                username=$.trim(username);
                password=$.trim(password);
                if(username!=null&&username.length>0&&password!=null&password.length>0){
                    flag=true;
                }else{
                    alert("不能为空");
                }
                return flag;
            });
        });
    </script>
</head>

  <body>
   <form action="/day31/register" method="post">
          <table border="2" align="center">
              <caption><h3>新用户注册(struts2版本)</h3></caption>
              <tr>
                  <th>用户名</th>
                  <td><input type="text" name="username" maxlength="10"/></td>
              </tr>
              <tr>
                  <th>密码</th>
                  <td><input type="text" name="password" maxlength="6"/></td>
              </tr>
              <tr>
                  <td colspan="2" align="center">
                      <input type="submit" value="注册"/>
                  </td>
              </tr>
          </table>
      </form>
  </body>
</html>

/day31/WebRoot/WEB-INF/register_success.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
    注册成功<br/>
    用户名:${requestScope.username}<br/>    
    密  码:${requestScope.password}<br/>  
  <!-- 底层调用get方法 --> </body> </html>

二:/day31/src/cn/itcast/web/struts2/user/UserAction.java

package cn.itcast.web.struts2.user;

public class UserAction {
        //表单参数
        private String username;
        private String password;
        //提供对应的setter方法(拦截器会将表单参数通过setter方法自动注入进来)
        public void setUsername(String username) {
            this.username = username;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        //EL取值,提供对应的getter方法 和拦截器栈有关
        public String getUsername() {
            return username;
        }
        public String getPassword() {
            return password;
        }
        //注册的业务控制方法 
        public String registerMethod(){
            System.out.println("用户名:" + username);
            System.out.println("密码:" + password);
            return "success";
        }
}

拦截器会默认将Action类的实例变量绑定在request域对象中,默认是空值,框架让拦截器将实例变量的值注入(setUsername("qe")),将转发改为重定向

<result name="success" type="redirect">
/register_success.jsp
</result>

改之后在success.jsp中不能取出值(重定向不是一个request)

[问题:用redirect时放在WEB-INF下访问不到]


*六)Action中业务方法的验证【数据格式的验证,属于后台验证】
(1)在Action中写多个类似的业务控制方法
相类似的业务控制方法,应该放在同一个Action中。

/day31/WebRoot/login.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
   <form action="/day31/login" method="post">
          <table border="2" align="center">
              <caption><h3>用户登录(struts2版本)</h3></caption>
              <tr>
                  <th>用户名</th>
                  <td><input type="text" name="username" maxlength="10"/></td>
               </tr>
              <tr>
                  <td colspan="2" align="center">
                      <input type="submit" value="登录"/>
                  </td>
              </tr>
          </table>
      </form>
  </body>
</html>

/day31/WebRoot/WEB-INF/login_success.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
    登录成功<br/>
    用户名:${requestScope.username}<br/>    
  </body>
</html>

/day31/src/cn/itcast/web/struts2/validator/ValidatorUserAction.java

package cn.itcast.web.struts2.validator;

import com.opensymphony.xwork2.ActionSupport;

//演示表单验证【后台】
public class ValidatorUserAction {
    private String username;//哈哈
    private String password;//NULL
    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 registerMethod(){
        return "registerSuccess";
    }
    //登录业务控制方法[后] 
    public String loginMethod(){
        return "loginSuccess";
    }
}

/day31/src/cn/itcast/web/struts2/validator/struts_validator.xml

<?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>
    <package name="validator" extends="struts-default" namespace="/">
    
        <!-- 用户注册 -->
        <action 
            name="register" 
            class="cn.itcast.web.struts2.validator.ValidatorUserAction" 
            method="registerMethod">
            <result name="registerSuccess" type="dispatcher">
                /WEB-INF/register_success.jsp    
            </result>    
        </action>        

        <!-- 用户登录-->
        <action 
            name="login" 
            class="cn.itcast.web.struts2.validator.ValidatorUserAction" 
            method="loginMethod">
            <result name="loginSuccess" type="dispatcher">
                /WEB-INF/login_success.jsp    
            </result>        
        </action>        
        
    </package>    
</struts>  

struts.xml包含

<include file="cn/itcast/web/struts2/validator/struts_validator.xml"/>


(2)验证Action中所有业务控制方法【validate()】
validate()针对Action中的每一个业务控制方法而言。

(4)收集Action中验证失败的消息,在jsp页面中显示【<s:fielderror fieldName="username"/>】
【用户注册和登录】

/day31/src/cn/itcast/web/struts2/validator/ValidatorUserAction.java

package cn.itcast.web.struts2.validator;

import com.opensymphony.xwork2.ActionSupport;

//演示表单验证【后台】
public class ValidatorUserAction extends ActionSupport{
    private String username;//哈哈
    private String password;//NULL
    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;
    }
    //---------------------------------------以下是针对所有业务控制的验证方法
    
        @Override
        public void validate() {
            //在set方法传入之后由框架(栈中的某个拦截器)调用,会把错误消息放到一个集合中,如果集合为空或长度为0则验证成功
            //验证成功,调用下面的业务控制方法;验证失败,调用input属性所指明的页面
            //ActionSupport的TextProvider接口负责错误消息的绑定
            if(this.username!=null && this.username.trim().length()>0){
                ;
            }else{
                //收集错误消息
                this.addFieldError("username","用户名必填");//("域名称","错误消息")
            }
            if(this.password!=null && this.password.trim().length()>0){
                ;
            }else{
                this.addFieldError("password","密码必填");
            }
        }    
    //---------------------------------------以下是业务控制方法
    
    //注册业务控制方法[再] 
    public String registerMethod(){
        return "registerSuccess";
    }
    //登录业务控制方法[后] 
    public String loginMethod(){
        return "loginSuccess";
    }
}

/day31/src/cn/itcast/web/struts2/validator/struts_validator.xml

<?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>
    <package name="validator" extends="struts-default" namespace="/">
    
        <!-- 用户注册 -->
        <action 
            name="register" 
            class="cn.itcast.web.struts2.validator.ValidatorUserAction" 
            method="registerMethod">
            <result name="registerSuccess" type="dispatcher">
                /WEB-INF/register_success.jsp    
            </result>
            <!-- 出错后,框架会调用input属性所对应的页面 -->
            <result name="input" type="dispatcher">
                /register.jsp
            </result>    
        </action>        

        <!-- 用户登录-->
        <action 
            name="login" 
            class="cn.itcast.web.struts2.validator.ValidatorUserAction" 
            method="loginMethod">
            <result name="loginSuccess" type="dispatcher">
                /WEB-INF/login_success.jsp    
            </result>    
            <!-- 出错后,框架会调用input属性所对应的页面 -->
            <result name="input" type="dispatcher">
                /login.jsp
            </result>    
        </action>        
        
    </package>    
</struts>      

/day31/WebRoot/register.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <script type="text/javascript" src="js/jquery-1.8.2.js"></script>
    <script type="text/javascript" >
        $(function(){
            $("form").submit(function(){
                var flag=false;
                var username=$(":text:first").val();
                var password=$(":text:last").val();
                username=$.trim(username);
                password=$.trim(password);
                if(username!=null&&username.length>0&&password!=null&password.length>0){
                    flag=true;
                }else{
                    alert("不能为空");
                }
                return flag;
            });
        });
    </script>
</head>

  <body>
   <form action="/day31/register" method="post">
          <table border="2" align="center">
              <caption><h3>新用户注册(struts2版本)</h3></caption>
              <tr>
                  <th>用户名</th>
                  <td><input type="text" name="username" maxlength="10"/></td>
                  <td>
                          <!-- 将出错的消息,取得并显示 -->
                          <s:fielderror fieldName="username"/>
                    </td>
              </tr>
              <tr>
                  <th>密码</th>
                  <td><input type="text" name="password" maxlength="6"/></td>
                     <td>
                          <s:fielderror fieldName="password"/>
                    </td>
              </tr>
              <tr>
                  <td colspan="2" align="center">
                      <input type="submit" value="注册"/>
                  </td>
              </tr>
          </table>
      </form>
  </body>
</html>

/day31/WebRoot/login.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
   <form action="/day31/login" method="post">
          <table border="2" align="center">
              <caption><h3>用户登录(struts2版本)</h3></caption>
              <tr>
                  <th>用户名</th>
                  <td><input type="text" name="username" maxlength="10"/></td>
                  <td>
                      <!-- 将出错的消息,取得并显示 -->
                      <s:fielderror fieldName="username"/>
                  </td>
               </tr>
              <tr>
                  <td colspan="2" align="center">
                      <input type="submit" value="登录"/>
                  </td>
              </tr>
          </table>
      </form>
  </body>
</html>

定义一个Action类时的几种语法方式: 
(1) 直接实现自己的Action(2) 实现Action接口 (3) 继承ActionSupport接口  

ActionSupport接口实现的接口: 
(1) Action接口:提供5个常量和一个excute()方法。 
(2) Validateable接口:提供validate()方法,重写此方法可以对表单数据进行验证。 

(3) ValidationAware接口:该接口定义了一些方法来对Action执行过程中产生的信息进行处理。 
(4) TextProvider接口:该接口提供了一系列getText()方法,用于获取国际化资源信息。 
(5) LocalProvider接口:提供一个getLocal()方法,用于国际化时获取语言。

 

(3)验证Action中某个业务控制方法【validateXxx()】

validateXxx()针对Action中的某一个业务控制方法而言。Xxx表示业务控制方法的名称,第一X大写。业务控制方法,就是与execute同签名的方法

当一个Action中,同时出现validate()和validateXxx()方法时,按如下次序执行:
validateXxx()    validate()    registerMethod()[如果验证成功了,才会执行xxx方法]

 /day31/src/cn/itcast/web/struts2/validator/ValidatorUserAction.java

package cn.itcast.web.struts2.validator;

import com.opensymphony.xwork2.ActionSupport;

//演示表单验证【后台】
public class ValidatorUserAction extends ActionSupport{
    private String username;//哈哈
    private String password;//NULL
    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;
    }
    //---------------------------------------以下是争对所有业务控制的验证方法
    @Override
    public void validate() {
    }    
    //---------------------------------------以下是争对某个业务控制的验证方法
    
    //专用于注册验证方法[先]
    public void validateRegisterMethod(){
        if(this.username!=null && this.username.trim().length()>0){
            if(this.username.matches("[\u4E00-\uFA29]+")){
                ;
            }else{
                this.addFieldError("username","用户名必填是中文");
            }
        }else{
            this.addFieldError("username","用户名必填");
        }
        if(this.password!=null && this.password.trim().length()>0){
            if(this.password.matches("[0-9]{6}")){
                ;
            }else{
                this.addFieldError("password","密码必须是6位数字");
            }
        }else{
            this.addFieldError("password","密码必填");
        }
    }        
    //专用于登录验证方法[先]
    public void validateLoginMethod(){
        if(this.username!=null && this.username.trim().length()>0){
            if(this.username.matches("[\u4E00-\uFA29]+")){
                
            }else{
                this.addFieldError("username","用户名必填是中文");
            }
        }else{
            this.addFieldError("username","用户名必填");
        }
    }            
        
    //---------------------------------------以下是业务控制方法
    
    //注册业务控制方法[再] 
    public String registerMethod(){
        return "registerSuccess";
    }
    //登录业务控制方法[后] 
    public String loginMethod(){
        return "loginSuccess";
    }
}

 

posted on 2016-07-27 10:28  step_step  阅读(2614)  评论(0编辑  收藏  举报

导航