Struts2 validate校驗

通常的,用戶註冊的時候,咱們須要校驗一些用戶提交過來的參數。css

通常有兩道屏障,一是在前臺頁面上使用js進行驗證,直接杜絕了不正常信息的提交。二是將提交過來的信息進行驗證,不經過則返回註冊頁面並顯示錯誤信息,咱們這裏介紹的就是在action中使用validate方法實現數據校驗。html

action中是繼承自ActionSupport類,ActionSupport實現了Validate接口,有一個空的validate方法。java

在action中只須要重寫一下validate方法就行了。運行程序的時候,會先執行validate方法而後執行execute()方法。jsp

在validate方法中,有這三種增長ActionError的方法,通常咱們使用第一中和第三種,一旦action中存在error,就表示校驗未經過,action自動返回INPUT,能夠在INPUT定義的result頁面中接受錯誤提示。ide

使用ActionError:post

使用addActionError方法增長錯誤進入ActionError中,ActionError是List格式ui

在jsp中使用<s:actionerror />展現錯誤信息this

regist.jsp:spa

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'regist.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <h1><font color="blue">註冊信息</font></h1>
    <s:actionerror cssStyle="color:red;"/>
     <form action="regist.action" method="post">
      username:<input type="text" name="username" size="20"/><br/>
      password:<input type="password" name="password" size="20"/><br/>
      repassword:<input type="password" name="repassword" size="20"/><br/>
      sex:<input type="text" name="sex" size="20"/><br/>
      age:<input type="text" name="age" size="20"/><br/>
      birthday:<input type="text" name="birthday" size="text"/><br/>
      graduation:<input type="text" name="graduation" size="20"/><br/>
      <input type="submit" value="submit"/>
     </form>
  </body>
</html>
View Code

struts.xml:code

        <action name="regist" class="com.shensiyuan.struts.action.RegistAction">
           <result name="success">/registResult.jsp</result>
           <result name="input">/regist.jsp</result>
        </action>
View Code

RegistAction.java:

package com.shensiyuan.struts.action;

import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.opensymphony.xwork2.ActionSupport;

public class RegistAction extends ActionSupport {
    private String username;
    private String password;
    private String repassword;
    private String sex;
    private int age;
    private Date birthday;
    private Date graduation;
    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 getRepassword() {
        return repassword;
    }
    public void setRepassword(String repassword) {
        this.repassword = repassword;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public Date getGraduation() {
        return graduation;
    }
    public void setGraduation(Date graduation) {
        this.graduation = graduation;
    }
    
    public String execute(){
        return SUCCESS;
    }
    @Override
    public void validate(){
        /**
         * 字符串使用正則驗證,3步:
         * 一、將string變爲正則對象  Pattern p1 = Pattern.compile(reg1);
         * 二、Matcher m = p1.matcher(username);
         * 三、 boolean b = m.matches();
         * 4這等價於前面3步: boolean b = Pattern.matches("a*b", "aaaaab");
         */
        String reg1="^[0-9a-zA-Z]{4,8}$";
        String reg2="^(wo)?man$";
       // String reg3="^([01]\\d\\d\\d\\|[2][0]\\d\\d)-([0][1-9]|[1][0-2])\\-([0-2][0-9]|[3][01])$"; 使用下面的方法是用正則,不須要將正則的String字符串先後加//
        //System.out.println(username);
        boolean usn=Pattern.matches(reg1, username);
        boolean ps=Pattern.matches(reg1, password);
        boolean reps=password.equals(repassword);
        boolean sx=Pattern.matches(reg2, sex);
        boolean ag=(age>0&&age<=100);
        boolean tm=false;
        if(birthday!=null&&graduation!=null){
             Calendar bir=Calendar.getInstance();
             bir.setTime(birthday);
             Calendar gra=Calendar.getInstance();
             gra.setTime(graduation);
             tm=(bir.before(gra));
        }
       if(!usn){
           this.addActionError("username should size in four to eight!");
       }
       if(!ps){
           this.addActionError("password should size in four to eight!");
       }
       if(!reps){
           this.addActionError("repassword should be same as password!");
       }
       if(!sx){
           this.addActionError("sex should be man or woman");
       }
       if(!ag){
           this.addActionError("age should between zero and hundred!");
       }
       if(!tm){
           this.addActionError("if exist,birthday shoule before graduation!");
       }
    }

}
View Code

registResult.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'registResult.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    username:<s:property value="username"/><br/>
    password:<s:property value="password"/><br/>
    repassword:<s:property value="repassword"/><br/>
    sex:<s:property value="sex"/><br/>
    age:<s:property value="age"/><br/>
    birthday:<s:property value="birthday"/><br/>
    graduation:<s:property value="graduation"/><br/>
  </body>
</html>
View Code

一組效果圖:

 

使用fielderror:

在action中的addFielderror增長錯誤,前面一個參數是錯誤的key,後裔個參數是錯誤的value,Fielderror是Map格式

顯示Field使用<s:fielderror />struts標籤

regist.jsp:

 <body>
    <h1><font color="blue">註冊信息</font></h1>
    <s:actionerror cssStyle="color:red;"/>
    
    --------------------
    <s:fielderror cssStyle="color:blue;"></s:fielderror>
    
     <form action="regist.action" method="post">
      username:<input type="text" name="username" size="20"/><br/>
      password:<input type="password" name="password" size="20"/><br/>
      repassword:<input type="password" name="repassword" size="20"/><br/>
      sex:<input type="text" name="sex" size="20"/><br/>
      age:<input type="text" name="age" size="20"/><br/>
      birthday:<input type="text" name="birthday" size="text"/><br/>
      graduation:<input type="text" name="graduation" size="20"/><br/>
      <input type="submit" value="submit"/>
     </form>
</body>
View Code

RegistAction.jsp:

public void validate(){
        /**
         * 字符串使用正則驗證,3步:
         * 一、將string變爲正則對象  Pattern p1 = Pattern.compile(reg1);
         * 二、Matcher m = p1.matcher(username);
         * 三、 boolean b = m.matches();
         * 4這等價於前面3步: boolean b = Pattern.matches("a*b", "aaaaab");
         */
        String reg1="^[0-9a-zA-Z]{4,8}$";
        String reg2="^(wo)?man$";
       // String reg3="^([01]\\d\\d\\d\\|[2][0]\\d\\d)-([0][1-9]|[1][0-2])\\-([0-2][0-9]|[3][01])$"; 使用下面的方法是用正則,不須要將正則的String字符串先後加//
        //System.out.println(username);
        boolean usn=Pattern.matches(reg1, username);
        boolean ps=Pattern.matches(reg1, password);
        boolean reps=password.equals(repassword);
        boolean sx=Pattern.matches(reg2, sex);
        boolean ag=(age>0&&age<=100);
        boolean tm=false;
        if(birthday!=null&&graduation!=null){
             Calendar bir=Calendar.getInstance();
             bir.setTime(birthday);
             Calendar gra=Calendar.getInstance();
             gra.setTime(graduation);
             tm=(bir.before(gra));
        }
       if(!usn){
           this.addActionError("username should size in four to eight!");
           this.addFieldError("username","username should size in four to eight!");
       }
       if(!ps){
           this.addActionError("password should size in four to eight!");
       }
       if(!reps){
           this.addActionError("repassword should be same as password!");
       }
       if(!sx){
           this.addActionError("sex should be man or woman");
       }
       if(!ag){
           this.addActionError("age should between zero and hundred!");
       }
       if(birthday==null){
           this.addActionError("birthday invalid!");
       }
       if(graduation==null){
           this.addActionError("graduation invalid!");
       }
       if(!tm){
           this.addActionError("if exist,birthday shoule before graduation!");
       }
    }
View Code

 

若是jsp頁面使用的是struts標籤編寫的form表單,而且<s:form/>的theme屬性不等於simple,則默認jsp中也會展現一遍fielderror中的內容

regist.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'regist.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <h1><font color="blue">註冊信息</font></h1>
    <s:actionerror cssStyle="color:red;"/>
    
    --------------------
    <s:fielderror cssStyle="color:blue;"></s:fielderror>
    
    <!-- 
     <form action="regist.action" method="post">
      username:<input type="text" name="username" size="20"/><br/>
      password:<input type="password" name="password" size="20"/><br/>
      repassword:<input type="password" name="repassword" size="20"/><br/>
      sex:<input type="text" name="sex" size="20"/><br/>
      age:<input type="text" name="age" size="20"/><br/>
      birthday:<input type="text" name="birthday" size="text"/><br/>
      graduation:<input type="text" name="graduation" size="20"/><br/>
      <input type="submit" value="submit"/>
     </form>
      -->
      <s:form action="regist.action" theme="">
      username:<s:textfield name="username" label="username"></s:textfield><br/>
      password:<s:password name="password" label="password"></s:password><br/>
      repassword:<s:password name="repassword" label="repassword"></s:password><br/>
      sex:<s:textfield name="sex" label="sex"></s:textfield><br/>
      age:<s:textfield name="age" label="age"></s:textfield><br/>
      birthday:<s:textfield name="birthday" label="birthday"></s:textfield><br/>
      graduation:<s:textfield name="graduation" label="graduation"></s:textfield><br/>
      <s:submit value="submit"></s:submit><br/>
      </s:form>
  </body>
</html>
View Code

效果:

 

actionerror與fielderror區別:

不說增長和展現以及存儲形式

當使用轉換不了的類型進行表單提交的時候,由於轉換異常,屬性得到的爲空。在actionerror中依舊進行校驗而後增長對應的錯誤信息;在fielderror中,若是轉換錯誤,自動在fielderror中增長對應的轉換錯誤的信息,該信息是默認的。

好比:

 在類型轉換中出現錯誤fielderror增長默認錯誤信息在form表單使用的不是struts標籤仍然有效。

相關文章
相關標籤/搜索