(5)表單Action後臺驗證

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

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.jsphtml

<%@ 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.jspjava

<%@ 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.javajquery

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")),將轉發改成重定向web

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

改以後在success.jsp中不能取出值(重定向不是一個request)框架

[問題:用redirect時放在WEB-INF下訪問不到]jsp


*六)Action中業務方法的驗證【數據格式的驗證,屬於後臺驗證】
(1)在Action中寫多個相似的業務控制方法
相相似的業務控制方法,應該放在同一個Action中。
ide

/day31/WebRoot/login.jsppost

<%@ 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";
    }
}
相關文章
相關標籤/搜索