Struts使用验证框架验证数据校验

Struts使用验证框架验证数据校验

.ActionSupport验证简单实现:

  第一步:导入jar


  第二步:配置过滤器web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>StrutsValidate</display-name>

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

  <filter>

    <filter-name>struts2</filter-name>   <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

  </filter>

  <filter-mapping>

     <filter-name>struts2</filter-name>

     <url-pattern>/*</url-pattern>

  </filter-mapping>

</web-app>

第三步:添加struts.xml(后续配置)

 

第四步:实体类:

package entity;

 

public class User {

       private String username;

       private String password;

       private Integer age;

       private String email;

 

       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 Integer getAge() {

              return age;

       }

 

       public void setAge(Integer age) {

              this.age = age;

       }

 

       public String getEmail() {

              return email;

       }

 

       public void setEmail(String email) {

              this.email = email;

       }

 

       @Override

       public String toString() {

              return "User [username=" + username + ", password=" + password

                            + ", age=" + age + ", email=" + email + "]";

       }

 

}

第五步:rejister.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%@taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

  <title>注册页面</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">

 

  </head>

  <body>

    <!-- 判断字段是否有错误信息 -->

    <s:if test="hasFieldError()">

       <h1 align="center">输出错误字段信息</h1>

       <div align="center" style="color: blue;">

          使用s:fielderror输出一个指定的错误信息

          <s:fielderror name="user.username">

             使用s:fielderror输出全部的错误信息

          </s:fielderror>

       </div>

    </s:if> 

    <!-- 判断action是否有错误 -->

     <s:if test="hasActionError()">

      <h1 align="center">输出错误Action信息</h1>

       <div align="center" style="color: gray;">

          使用s:actionerror输出action相关的错误信息

          <s:actionerror/>

       </div>

     </s:if>

     <h1>使用execute业务方法直接校验</h1>

     <s:form action="register.action" method="post">

        <s:textfield label="用户名" name="user.username"/>

        <s:password label="密码" name="user.password"/>

        <s:textfield label="年龄" name="user.age"/>

        <s:textfield label="邮箱" name="user.email"/>

        <s:submit value="提交" />

        <s:reset value="重置"/>

     </s:form>

     <s:debug/>

  </body>

</html>

第六步:registeSuccess.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

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 'index.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">

 

  </head>

 

  <body>

    登录成功!

  </body>

</html>

第七步:Action类编写:

package action;

 

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

import com.opensymphony.xwork2.ActionSupport;

 

import entity.User;

 

public class UserAction extends ActionSupport{

       private User user;

       @Override

       public String execute() throws Exception {

              if (null==user.getUsername()||"".equals(user.getUsername())) {

                     this.addFieldError("user.username","用户名不能为空");

              }

              if (null==user.getPassword()||"".equals(user.getPassword())) {

                     this.addFieldError("user.password", "密码不能为空");

              }

              /*

               * ^ 表示以什么开通,$ 表示以什么结尾

           {x,y} 表示字符的长度,x~y

                      表示后面必须跟数字,数字的长度为1~3个,就是说1个,2个,3个都可以

               */

              String ageStr="^\\d{1,3}$"; 

              Pattern ageReg=Pattern.compile(ageStr);   //编译

              Matcher ageMatcher=ageReg.matcher(user.getAge()+"");  //测试

              if (!ageMatcher.matches()) {

                     this.addFieldError("user.age","年龄只能是数字,并只能为1-200之间");

              }

              if (null==user.getAge()) {

                     this.addFieldError("user.age", "年龄不能为空");

              }

              String emaString="^\\w+@\\w+(.\\w{2,3}){1,2}$";

              Pattern emailReg=Pattern.compile(emaString);

              Matcher emailMatcher=emailReg.matcher(user.getEmail());

              if (!emailMatcher.matches()) {

                     this.addFieldError("user.email","邮箱格式不正确");

              }

              if (this.hasErrors()) {

                  this.addActionError("输入的注册信息不正确!");

                  return INPUT;

              }

             

              return SUCCESS;

       }

       public User getUser() {

              return user;

       }

       public void setUser(User user) {

              this.user = user;

       }

}

第八步:配置Struts.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

       "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"

       "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

      <constant name="struts.enable.DynamicMethodInvocation" value="false"></constant>

      <constant name="struts.devMode" value="true"></constant>

    <package name="default" namespace="/" extends="struts-default">

       <action name="register" class="action.UserAction">

                <result name="input">/register.jsp</result>

                <result name="success">/registerSuccess.jsp</result>

        </action>

    </package>

</struts>

第九步:测试运行:



二.使用重写ActionSuppor类中Validate()方法

只更改action类

package action;

 

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

import com.opensymphony.xwork2.ActionSupport;

 

import entity.User;

 

public class UserAction extends ActionSupport{

       private User user;

       @Override

       public String execute() throws Exception {

              if (this.hasErrors()) {

                  this.addActionError("输入的注册信息不正确!");

                  return INPUT;

              }

             

              return SUCCESS;

       }

       @Override

       public void validate() {

              if (null==user.getUsername()||"".equals(user.getUsername())) {

                     this.addFieldError("user.username","用户名不能为空");

              }

              if (null==user.getPassword()||"".equals(user.getPassword())) {

                     this.addFieldError("user.password", "密码不能为空");

              }

              /*

               * ^ 表示以什么开通,$ 表示以什么结尾

           {x,y} 表示字符的长度,x~y

                      表示后面必须跟数字,数字的长度为1~3个,就是说1个,2个,3个都可以

               */

              String ageStr="^\\d{1,3}$"; 

              Pattern ageReg=Pattern.compile(ageStr);   //编译

              Matcher ageMatcher=ageReg.matcher(user.getAge()+"");  //测试

              if (!ageMatcher.matches()) {

                     this.addFieldError("user.age","年龄只能是数字,并只能为1-200之间");

              }

              if (null==user.getAge()) {

                     this.addFieldError("user.age", "年龄不能为空");

              }

              String emaString="^\\w+@\\w+(.\\w{2,3}){1,2}$";

              Pattern emailReg=Pattern.compile(emaString);

              Matcher emailMatcher=emailReg.matcher(user.getEmail());

              if (!emailMatcher.matches()) {

                     this.addFieldError("user.email","邮箱格式不正确");

              }

              super.validate();

       }

       public User getUser() {

              return user;

       }

       public void setUser(User user) {

              this.user = user;

       }

}

三.使用validateXXX(),针对一个业务方法进行数据验证

更改action类和struts.xml

Action类更改如下:

package action;

 

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

import com.opensymphony.xwork2.ActionSupport;

 

import entity.User;

 

public class UserAction extends ActionSupport{

       private User user;

        

       public String register() throws Exception {

              if (this.hasErrors()) {

                  this.addActionError("输入的注册信息不正确!");

                  return INPUT;

              }

             

              return SUCCESS;

       }

       @Override

       public void validate() {

              if (null==user.getUsername()||"".equals(user.getUsername())) {

                     this.addFieldError("user.username","用户名不能为空");

              }

              if (null==user.getPassword()||"".equals(user.getPassword())) {

                     this.addFieldError("user.password", "密码不能为空");

              }

               

       }

       public void validateRegister(){

              /*

               * ^ 表示以什么开通,$ 表示以什么结尾

           {x,y} 表示字符的长度,x~y

                      表示后面必须跟数字,数字的长度为1~3个,就是说1个,2个,3个都可以

               */

              String ageStr="^\\d{1,3}$"; 

              Pattern ageReg=Pattern.compile(ageStr);   //编译

              Matcher ageMatcher=ageReg.matcher(user.getAge()+"");  //测试

              if (!ageMatcher.matches()) {

                     this.addFieldError("user.age","年龄只能是数字,并只能为1-200之间");

              }

              if (null==user.getAge()) {

                     this.addFieldError("user.age", "年龄不能为空");

              }

              String emaString="^\\w+@\\w+(.\\w{2,3}){1,2}$";

              Pattern emailReg=Pattern.compile(emaString);

              Matcher emailMatcher=emailReg.matcher(user.getEmail());

              if (!emailMatcher.matches()) {

                     this.addFieldError("user.email","邮箱格式不正确");

              }

               

       }

      

      

       public User getUser() {

              return user;

       }

       public void setUser(User user) {

              this.user = user;

       }

}

Struts.xml配置如下:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

       "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"

       "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

      <constant name="struts.enable.DynamicMethodInvocation" value="false"></constant>

      <constant name="struts.devMode" value="true"></constant>

    <package name="default" namespace="/" extends="struts-default">

       <action name="register" class="action.UserAction" method="register">

                <result name="input">/register.jsp</result>

                <result name="success">/registerSuccess.jsp</result>

        </action>

    </package>

</struts>

四.使用验证框架

修改action类,添加UserAction-validation.xml,保持上述三中的struts.xml

Action类:

package action;

 

import com.opensymphony.xwork2.ActionSupport;

 

import entity.User;

 

public class UserAction extends ActionSupport{

       private User user;

       public String register() throws Exception {

              if (this.hasErrors()) {

                  this.addActionError("输入的注册信息不正确!");

                  return INPUT;

              }

             

              return SUCCESS;

       }

       public User getUser() {

              return user;

       }

       public void setUser(User user) {

              this.user = user;

       }

}

UserAction-validation.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"

        "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">

<validators>

       <!-- 用户名验证 -->

       <field name="user.username">

              <field-validator type="requiredstring">

                     <param name="trim">true</param>

                     <message>用户名不能为空!</message>

              </field-validator>

              <field-validator type="stringlength">

                     <param name="minLength">4</param>

                     <param name="maxLength">16</param>

                     <param name="trim">true</param>

                     <message>用户名必须为${minLength}至${maxLength}个字符!,当前为${user.username}

                     </message>

              </field-validator>

       </field>

       <!--密码 -->

       <field name="user.password">

              <field-validator type="requiredstring">

                     <param name="trim">true</param>

                     <message>密码不能为空!</message>

              </field-validator>

              <field-validator type="stringlength">

                     <!--去掉前后的空格 -->

                     <param name="trim">true</param>

                     <param name="minLength">6</param>

                     <param name="maxLength">20</param>

                     <message>密码必须为${minLength}至${maxLength}个字符,当前为${user.password}

                     </message>

              </field-validator>

       </field>

       <!--年龄 -->

       <field name="user.age">

              <field-validator type="required">

                     <param name="trim">true</param>

                     <message>年龄不能为空</message>

              </field-validator>

              <field-validator type="int">

                     <param name="trim">true</param>

                     <param name="min">1</param>

                     <param name="max">200</param>

                     <message>年龄为${min}---${max}岁之间</message>

              </field-validator>

       </field>

       <field name="user.email">

              <field-validator type="requiredstring">

                     <param name="trim">true</param>

                     <message>邮箱不能为空</message>

              </field-validator>

              <field-validator type="email">

                     <param name="trim">true</param>

                     <message>邮箱格式不正确!</message>

              </field-validator>

       </field>

</validators>

五.针对一个业务进行配置文件

将上面的年龄验证和邮箱验证独立出来

1.改变UserAction-validation.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"

        "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">

<validators>

       <!-- 用户名验证 -->

       <field name="user.username">

              <field-validator type="requiredstring">

                     <param name="trim">true</param>

                     <message>用户名不能为空!</message>

              </field-validator>

              <field-validator type="stringlength">

                     <param name="minLength">4</param>

                     <param name="maxLength">16</param>

                     <param name="trim">true</param>

                     <message>用户名必须为${minLength}至${maxLength}个字符!,当前为${user.username}

                     </message>

              </field-validator>

       </field>

       <!--密码 -->

       <field name="user.password">

              <field-validator type="requiredstring">

                     <param name="trim">true</param>

                     <message>密码不能为空!</message>

              </field-validator>

              <field-validator type="stringlength">

                     <!--去掉前后的空格 -->

                     <param name="trim">true</param>

                     <param name="minLength">6</param>

                     <param name="maxLength">20</param>

                     <message>密码必须为${minLength}至${maxLength}个字符,当前为${user.password}

                     </message>

              </field-validator>

       </field>

      

</validators>

添加UserAction-register-validation.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"

        "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">

<validators>

      

       <!--年龄 -->

       <field name="user.age">

              <field-validator type="required">

                     <param name="trim">true</param>

                     <message>年龄不能为空</message>

              </field-validator>

              <field-validator type="int">

                     <param name="trim">true</param>

                     <param name="min">1</param>

                     <param name="max">200</param>

                     <message>年龄为${min}---${max}岁之间</message>

              </field-validator>

       </field>

       <field name="user.email">

              <field-validator type="requiredstring">

                     <param name="trim">true</param>

                     <message>邮箱不能为空</message>

              </field-validator>

              <field-validator type="email">

                     <param name="trim">true</param>

                     <message>邮箱格式不正确!</message>

              </field-validator>

       </field>

</validators>

资料参考网址:https://www.cnblogs.com/liunanjava/p/4383237.html

【提示:参考网址的内容特别详细。如果需要写好的源码,点击以下链接:】

源代码:

http://download.csdn.net/download/qq_25337221/10129073

 微笑本内容由安康学院"雨季"原创!

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值