所有的学习我们必须先搭建好Struts2的环境(1、导入对应的jar包,2、web.xml,3、struts.xml)

第一节:Struts2 验证简介

Struts2 基于Struts2 拦截器,为开发者提供了一套易用的验证框架,并可扩展;一般的验证都支持。

第二节:Struts2 内置验证

一,普通字段验证

二,验证表达式:

<s:actionerror/>(在配置信息中最后“用户名和真实姓名不能相同”的话,即表明有error,所以用表达式,在前端页面会有显示)

例子:

struts.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="manager" extends="struts-default"> <action name="registerAction" class="com.wishwzp.action.RegisterAction">
<result name="input">/register.jsp</result>
<result name="success">/success.jsp</result>
</action> </package> </struts>

User.java

 package com.wishwzp.model;

 public class User {

     private String userName;//用户名
private String name;//真实姓名
private int age;//年龄
private String email;//邮件
private String homePage;//主页 public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHomePage() {
return homePage;
}
public void setHomePage(String homePage) {
this.homePage = homePage;
}
@Override
public String toString() {
return "User [userName=" + userName + ", name=" + name + ", age=" + age
+ ", email=" + email + ", homePage=" + homePage + "]";
} }

RegisterAction.java

 package com.wishwzp.action;

 import com.wishwzp.model.User;
import com.opensymphony.xwork2.ActionSupport; public class RegisterAction extends ActionSupport{ /**
*
*/
private static final long serialVersionUID = 1L; private User user; public User getUser() {
return user;
} public void setUser(User user) {
this.user = user;
} @Override
public String execute() throws Exception {
System.out.println("传入的用户:"+user);
return SUCCESS;
} }

RegisterAction-validation.xml      (这个文件命名规范:XXXX-validation.xml,其中XXXX就是后台action类)

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd"> <validators> <!-- 用户名格式验证 -->
<field name="user.userName">
<field-validator type="requiredstring">
<message>请输入用户名</message>
</field-validator>
<field-validator type="stringlength">
<param name="minLength">6</param>
<param name="maxLength">10</param>
<message>用户名必须在${minLength}和${maxLength}之间</message>
</field-validator>
</field> <!-- 真实姓名格式验证 -->
<field name="user.name">
<field-validator type="requiredstring">
<message>请输入姓名</message>
</field-validator>
</field> <!-- 年龄格式验证 -->
<field name="user.age">
<field-validator type="int">
<param name="min">18</param>
<message>年龄必须满18周岁</message>
</field-validator>
</field> <!-- 邮件格式验证 -->
<field name="user.email">
<field-validator type="requiredstring">
<message>请输入邮件</message>
</field-validator>
<field-validator type="email">
<message>邮件格式不对</message>
</field-validator>
</field> <!-- 主页格式验证 -->
<field name="user.homePage">
<field-validator type="requiredstring">
<message>请输入主页</message>
</field-validator>
<field-validator type="url">
<message>主页格式不对</message>
</field-validator>
</field> <!-- 用户名和真实姓名不能相同验证 -->
<!-- !user.name.equals(user.userName) 用户名和真实姓名不能相等,如果相等就是错误的信息,前端页面会有"<s:actionerror>"表达式显示错误信息 -->
<validator type="expression">
<param name="expression"><![CDATA[!user.name.equals(user.userName)]]></param>
<message>用户名和真实姓名不能相同</message>
</validator>
</validators>

register.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body> <!-- 这是就是用户名和真实姓名错误后显示的信息 -->
<s:actionerror/> 用户注册
<s:form action="/registerAction" method="post">
<s:textfield name="user.userName" label="用户名"></s:textfield>
<s:textfield name="user.name" label="真实姓名"></s:textfield>
<s:textfield name="user.age" label="年龄"></s:textfield>
<s:textfield name="user.email" label="邮件"></s:textfield>
<s:textfield name="user.homePage" label="主页"></s:textfield>
<s:submit value="注册"></s:submit>
</s:form>
</body>
</html>

success.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
注册成功
</body>
</html>

结果显示:(什么都没有写就提交了的结果显示)

第三节:自定义验证

例子:

validators.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator Config 1.0//EN"
"http://struts.apache.org/dtds/xwork-validator-config-1.0.dtd">
<validators>
<validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/>
<validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/>
<validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/>
<validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/>
<validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/>
<validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/>
<validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/>
<validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/>
<validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/>
<validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/>
<validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/>
<validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/>
<validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/>
<validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/> <!-- 自己定义配置的validatiors验证敏感词汇 -->
<validator name="sensitive" class="com.wishwzp.validators.SensitiveWordValidators"/>
</validators>

SensitiveWordValidators.java

 package com.wishwzp.validators;

 import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport; public class SensitiveWordValidators extends FieldValidatorSupport{ @Override
public void validate(Object object) throws ValidationException {
String fieldName=this.getFieldName();//获取字段名称
String value=this.getFieldValue(fieldName, object).toString();//获取用户输入的值
if(!check(value)){
this.addFieldError(fieldName, object);
}
} public boolean check(String value){
String sensitiveWords[]={"你妹","你妈"};//敏感词汇
for(int i=0;i<sensitiveWords.length;i++){
if(value.indexOf(sensitiveWords[i])>-1){
return false;
}
}
return true;
} }

struts.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="manager" extends="struts-default"> <action name="validationAction" class="com.wishwzp.action.ValidationAction">
<result name="input">/validation.jsp</result>
<result name="success">/success.jsp</result>
</action> </package> </struts>

ValidationAction.java

 package com.wishwzp.action;

 import com.wishwzp.model.User;
import com.opensymphony.xwork2.ActionSupport; public class ValidationAction extends ActionSupport{ /**
*
*/
private static final long serialVersionUID = 1L; private String name; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public String execute() throws Exception {
System.out.println("姓名:"+name);
return SUCCESS;
} }

ValidationAction-validation.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd"> <validators>
<field name="name">
<field-validator type="requiredstring">
<message>请输入姓名</message>
</field-validator> <field-validator type="sensitive">
<message>有敏感词汇</message>
</field-validator>
</field> </validators>

validation.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
简单自定义验证
<s:form action="/validationAction" method="post">
<s:textfield name="name" label="姓名"></s:textfield>
<s:submit value="提交"></s:submit>
</s:form>
</body>
</html>

结果:

如果输入敏感词提交的话:

如果输入不是敏感词提交的话:

(七)Struts2 验证框架的更多相关文章

  1. 关于struts2 验证框架在联网的时候可以用,不联网不起作用的问题

    这是一个让我很头痛的问题,我是在一个其他的项目框架的基础上来开发新的项目. 当使用struts验证框架时,突然发现这个验证不起作用了,我就纳闷了之前用这个开发的项目好好的怎么到我这就不能用了呢? xm ...

  2. Struts2验证框架_xml验证失败

    测试Struts2验证框架-->XML验证   启动tomcat后网页登录失败 Employee-validation.xml文件头如下: <!DOCTYPE validators PUB ...

  3. JavaWeb -- Struts2 验证框架

    1. 验证框架 示例 表单提交Jsp, reg.jsp <%@ page language="java" contentType="text/html; chars ...

  4. Struts2验证框架实例

    今天写了个Struts验证框架的实例,总算把验证框架弄清楚了. 上一篇Struts实例的action没有继承ActionSupport类,虽然也可以实现action的功能,但是却不能应用Struts提 ...

  5. struts2学习(11)struts2验证框架1.验证简介、内置验证

    一.Struts2验证简介: 二.struts2内置验证: 下面例子,需求是:为用户注册进行验证: com.cy.model.User.java: package com.cy.model; publ ...

  6. Struts2 验证框架 validation.xml 常用的验证规则

    validation.xml 的命名规则和放置路径: 文件名:<ActionClassName>-validation.xml <ActionClassName>就是要验证的A ...

  7. struts2验证框架

    如何做一个工号 用户 密码 验证登录页面? 答:1,先画一个login.jsp ,如何画呢?先引入Struts2标签库,利用Struts2标签库画登录页面:如下: 2,先进入useractiion,在 ...

  8. struts2验证框架1

    <!--该属性指定需要Struts 2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts 2处理.如果用户需要指定多个请求后缀,则多个后缀之间以英文逗 ...

  9. struts2学习(12)struts2验证框架2.自定义验证

    一.例子需求: 对敏感词进行验证: 将struts包中的validators.xml文件拷贝一份到src目录下,在最后面添加自己的验证器: com.cy.validators.SensitiveWor ...

随机推荐

  1. 手动启动jenkins

    无论Linux还是windows, jenkins都是作为一个后台服务存在的. 所以在Linux下,手动启动或停止jenkins: service jenkins start service jenk ...

  2. Cookie及Session文件在本机的存放位置

    1. Cookie的存放位置 D:\Users\xlxiao\AppData\Roaming\Microsoft\Windows\Cookies 2. Session的存放位置(目前未解决)

  3. JavaScript---网络编程(4)-Date、Math、Global和自定义对象

    本节博客进行Date对象.Math对象.Global对象和自定义对象的用法演示. 首先是一个out.js文件内容(输出到网页中的自定义输出方法): function println(parma){ d ...

  4. HDOJ/HDU 1088 Write a simple HTML Browser(HTML字符串)

    Problem Description If you ever tried to read a html document on a Macintosh, you know how hard it i ...

  5. 转载: Asp.net常见word,excel,ppt,pdf在线预览方案

    参考链接: http://www.cnblogs.com/wolf-sun/p/3569960.html

  6. 洛谷1373 小a和uim之大逃离

    洛谷1373 小a和uim之大逃离 本题地址:http://www.luogu.org/problem/show?pid=1373 题目背景 小a和uim来到雨林中探险.突然一阵北风吹来,一片乌云从北 ...

  7. Bzoj 3236: [Ahoi2013]作业 莫队,分块

    3236: [Ahoi2013]作业 Time Limit: 100 Sec  Memory Limit: 512 MBSubmit: 1113  Solved: 428[Submit][Status ...

  8. openstack 调试

  9. 使用int?来确保值类型也可以为null

    基元类型为什么需要为null?考虑两个场景: 1)数据库中一个int字段可以被设置为null.在C#中,值被取出来后,为了将它赋值给int类型,不得不首先判断一下它是否为null.如果将null直接赋 ...

  10. General: Know How to Use InetAddress

    Modern applications often need the ability to learn information about hosts out on the network. One ...