输入校验主要分为两种:

  基于客户端的校验:

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

  基于服务端的校验:

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

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}$";

struts2之输入验证的更多相关文章

  1. Struts2的输入验证

    一.概述: ① Struts2的输入验证 –基于 XWorkValidation Framework的声明式验证:Struts2提供了一些基于 XWork Validation Framework的内 ...

  2. [原创]java WEB学习笔记70:Struts2 学习之路-- 输入验证,声明式验证,声明是验证原理

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  3. struts2的validate输入验证

    原创 struts2的输入验证有两种方式: 使用validate()方法实现验证 使用验证文件实现验证 下面通过一个例子介绍validate()方法验证——实现客户注册输入验证 设计的JSP页面代码: ...

  4. Struts2入门(四)——数据输入验证

    一.前言 1.1.什么是输入验证?为什么需要输入验证? 在上一篇文章中,我们学习了数据类型转换,我们提到了表示层数据处理的两个方法,也提到了用户输入数据需要进行类型转换才能得到我们想要的数据,那么,我 ...

  5. struts2输入验证

    1.方法     ① 基于Annotations的验证       ②基于XML配置的验证 http://blog.csdn.net/furongkang/article/details/692204 ...

  6. struts2系列(二):struts2参数传递错误、struts2的输入错误验证

    一.struts2参数传递错误 1. 基本数据类型的传递最好使用包装类,原因是struts 2.1之后使用基本数据类型如果参数为空会报错2. 日期参数的传递最好定义一个区域的属性(定义locale), ...

  7. Struts2的输入校验(1)——校验规则文件的编写

    Struts2的输入校验(1) --校验规则文件的编写 Struts2提供了基于验证框架的输入校验,所有的输入校验只要编写配置文件,Struts2的验证框架将会负责进行服务器校验和客户端校验. 注: ...

  8. Struts2框架(8)---Struts2的输入校验

    Struts2的输入校验 在我们项目实际开发中在数据校验时,分为两种,一种是前端校验,一种是服务器校验: 客户端校验:主要是通过jsp写js脚本,它的优点很明显,就是输入错误的话提醒比较及时,能够减轻 ...

  9. JavaWeb框架_Struts2_(六)----->Struts2的输入校验

    1. 输入校验章节目录 输入校验概述 客户端校验 服务器端校验 手动编程校验 重写validate方法 重写validateXxx()方法 输入校验流程 校验框架校验 Struts2 内置的校验器 常 ...

随机推荐

  1. php 关于时间的函数

    //返回1970年1月1日零点以来的秒数.    //定义为从格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数. time(); ...

  2. return break continue区别

    return:1.跳出整个方法体 2.返回值 function(a){return a=2}; break:跳出当前循环, continue:跳出当前判断继续执行

  3. ueditor 插件问题

  4. vue中 eCharts 自适应容器

    在 vue 脚手架开发中,echarts图表自适应容器的方法: 父组件: <template> <div class="statistics_wrap"> ...

  5. HTML超链接实用

    1.文本链接: <a href="http://www.meng.com/" target="_blank">访问meng!</a> 2 ...

  6. python模块详解 random os

    random模块 常用方法 random.random() 随机产生一个小于1的浮点数 import random print(random.random()) #0.4153761818276826 ...

  7. [bootstrap]模态框总结

    <!--data-backdrop禁止点击空白处关闭模态框,也可以js设置,其他参数可参考官网模态框文档--> <div class="modal fade" i ...

  8. HCNA配置浮动静态路由

    1.拓扑图 2.配置IP R1 Please press enter to start cmd line! ############ <Huawei> Dec ::-: Huawei %% ...

  9. C#获取农历的日期(转)

    //C# 获取农历日期 ///<summary> /// 实例化一个 ChineseLunisolarCalendar ///</summary> private static ...

  10. centos 7中磁盘挂载重启后挂载失效

     在centos 7磁盘挂载成功后,关机重启,挂载磁盘失效,需要重新挂载,不用重新挂载的开机挂载方法如下: 1.先检验要挂载的磁盘是否已被挂载,有的话先卸除 2.修改 /etc/fstab 文件 ,最 ...