struts2之输入验证

输入校验主要分为两种:

  基于客户端的校验:

    客户端校验主要作用是防止正常浏览者的误输入,仅能对输入进行初步过滤;对于一些用户恶意行为,客户端校验则无能为力。

  基于服务端的校验:

    服务器接收客户端提交的数据,对这些数据的合理性、安全性等进行进一步的判断处理。

1、重写validate方法

注册action:

package com.action;

import java.util.regex.Pattern;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import entity.User;  // 封装页面注册信息

public class ValidateAction extends ActionSupport {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    /**
     * 重写validate方法
     *     仅能针对execute()做输入校验
     */
    @Override
    public void validate() {
        System.out.println(user.getName());
        // 放入上下文中,页面可以通过${name }获取,在注册不成功时,让用户知道自己之前输错的信息
        ActionContext.getContext().put("pwd", user.getPwd());
        ActionContext.getContext().put("name", user.getName());
        ActionContext.getContext().put("age", user.getAge());
        // 验证规则
        if(user.getName() != null || "".equals(user.getName().trim())){
            if (user.getAge() < 18 || user.getAge() > 30) {
                this.addFieldError("errorMsg", "年龄必须在18到30岁");
            }
            if(Pattern.compile("^1[358]\\d{3}$").matcher(user.getPwd()).matches()){
                this.addFieldError("errorMsg", "密码不合规");
            }
        }
    }
}

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

  </head>
  
  <body>
      <h2>使用${fieldErrors['errorMsg'][0]}这种方法显示验证信息,在于action中赋值
      this.addFieldError("errorMsg", "年龄必须在18到30岁");
      </h2>
      <s:fielderror></s:fielderror>
       <form action="vaildate.action" method="post">
            用户名: <input type="text" name="user.name" value="${name }">
            密码: <input type="password" name="user.pwd" value="${pwd }">
            年龄: <input type="text" name="user.age" value="${age }">
        <input type="submit" value="注册"><h5>${fieldErrors['errorMsg'][0]}</h5>
       </form>
       <h2>另一种显示校验信息:
       使用struts标签,必须通过过滤器,故在web.xml配置jsp过滤规则,以下是struts标签显示验证信息</h2>
       <s:property value="fieldErrors['errorMsg'][0]"/>
       <h2>使用debug标签</h2>
       <s:debug></s:debug>
  </body>
</html>

struts.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "struts-2.3.dtd" >
<struts>
    <!-- 热部署 -->
    <constant name="struts.configuration.xml.reload" value="true"></constant>
    <!-- 动态方法调用 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>

    <package name="hello" namespace="/" extends="json-default">
        <!-- 注册的action -->
        <action name="reg" class="com.action.RegAction" method="reg">
            <result name="success">/index.jsp</result>        
        </action>
        <!-- 验证的action -->
        <action name="vaildate" class="com.action.ValidateAction">
            <!-- 验证通过 ,回到主页面-->
            <result name="success" type="chain">
                <param name="actionName">reg</param> 
            </result>
            <!-- 
                验证不通过,回到注册页面,显示验证信息
                注意这里的 input属性,否则会报错
             -->
            <result name="input">/reg.jsp</result>
        </action>
        
    </package>
</struts>   

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>struts2</display-name>
  
      <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>*.action</url-pattern>
    </filter-mapping>
    <!-- 配置jsp页面的过滤,使其可以使用struts标签 -->
    <filter-mapping>
         <filter-name>struts2</filter-name>
         <url-pattern>*.jsp</url-pattern>
    </filter-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

2、重写validateXxx方法

由于validate()方法只能对execute()进行输入校验,对于实际业务需求,我们需要根据对不同的方法做输入校验。

Struts2提供了一个validateXxx()方法,Xxx即是Action对应的处理逻辑方法名。

action类:

public class ValidateUserAction extends  ActionSupport {
      private  String  message;
      private  String account;//用户账号
      private  String password;//用户密码
      //用户登录
      public String  login(){//具体业务操作内容省略}
      public  void  validateLogin(){
           //用户输入的账号长度为6~12位,不允许有空格    
           if(!account.matches("^[^ ]{6,12}$")){
                this.addFieldError("account", "账号长度6~12位,不允许出现空格");
            }
           if(!password.matches("^[^ ]{6,15}$")){
                this.addFieldError(“password", "密码长度6~15位,不允许出现空格");
           }
        }
}
 

action配置:

<action name="validateUser"  class="com.pxy.struts.action.ValidateUserAction">
     <result name="input">/login.jsp</result>
     <result name="login">/success.jsp</result>
</action> 

 

常用的登录正则验证

//邮箱正则表达式
String  emailRegex="\\b^['_a-z0-9-\\+]+(\\.['_a-z0-9-\\+]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2}|aero|arpa|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|
name|nato|net|org|pro|tel|travel|xxx)$\\b";

//身份证号正则表达式
String  idCardRegex="(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])";

//手机号正则表达式
String  phoneNoRegex="^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";

 

posted @ 2018-02-19 17:04  x_jingxin  阅读(138)  评论(0编辑  收藏  举报