struts校验框架提供两种校验:客户端校验和服务端校验。它们都是主要检查浏览器输入数据是否合法的校验器。

  • 服务端校验

    服务端校验是在服务器上检查输入数据,它的实现方法是重写validate()方法。如果想对特定方法进行校验,须实现validate方法名()(方法名首字母大写)。

    

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport
{ /**
*
*/
private static final long serialVersionUID = 1L;
private String username ;
private String password; public LoginAction(){
System.out.println("constructor called!");
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
}
@Override
public String execute() throws Exception { if(username.equals(""))
return ERROR;
else{ context.getSession().put("username", username); return SUCCESS;
} }
public void validateExecute(){
System.out.println("validateExecute called!"); } public void validate(){
System.out.println("validate called!");
if(getUsername()==null || getUsername().trim().equals(""))
this.addFieldError("username", "必须输入用户名");
if(getPassword()==null || getUsername().trim().equals(""))
this.addFieldError("password", "必须输入密码"); } }

  

如执行结果,校验是先执行针对方法的校验,最后执行总的校验,所以在实现的过程中需要小心校验的覆盖问题。

  • 客户端校验

    这种校验的格式比较繁杂,它是在浏览器中执行的。实现struts2的客户端校验,首先需要写一个Action,配置好Action的input页面,再写一个ActionName-validate.xml文件,并且要把这个xml文件放在相应action的同一包下。

    Action:

    

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport{
private String username;
private String password;
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 execute(){ return SUCCESS;
}
}

    RegisterAction-validate.xml:

    

<?xml version="1.0" encoding="utf-8"?>
<!-- 指定校验配置文件的DTD信息 -->
<!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="username">
<field-validator type="requiredstring">
<message>users should be not blank!</message>
</field-validator> <field-validator type="stringlength">
<param name="minLength">6</param>
<param name="maxLength">10</param>
<message>users should be between ${minLength} and ${maxLength}</message>
</field-validator>
</field>
<field name="password" >
<field-validator type="requiredstring" short-circuit="true">
<param name="trim">true</param>
<message>should input password</message>
</field-validator> </field>
</validators>

    然后在页面表格上设置校验为true,struts的校验框架需要用s标签库。

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login2</title>
</head>
<body>
<s:form action="RegisterAction.action" validate="true">
<s:textfield name="username" label="用户名"></s:textfield>
<s:password name="password" label="密码"></s:password>
<s:submit value="注册"></s:submit>
</s:form>
</body>
</html>

    

    验证失败之后会返回input字符串    

     最后补充一下default.xml的校验器

<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="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/>
<validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/>
<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"/>
</validators>

    以及字段的意思:

      (1)field:需要校验的字段,name属性值需要和action中的字段一致;

      (2)field-validator:校验器,type属性值为struts2框架提供的校验器。路径为:项目导入的jar包xwork-core-2.3.16.3.jar/com.opensymphony.xwork2.validator.validators/default.xml

      (3)接着param是为type指定的校验器提供参数值,因为一个校验器对应一个java类,可以通过param标签为该类中的字段指定值。这里<param name="trim">true</param>意思是设置requiredstring校验器所引用的类com.opensymphony.xwork2.validator.validators.RequiredStringValidator中的字段trim的值为true,意思是对username属性值作去前后空格处理。

      (4)<message>用于发送错误信息

      (5)此外xml文件的模版可以在struts2官方提供的框架压缩包中找到,路径为:struts-2.3.16.3\src\xwork-core\src\main\resources

struts2校验总结的更多相关文章

  1. Struts2 校验

    Struts2校验格式: actionName-methodName-invalidation.xml  该配置文件必须和action类在同一个包下. <?xml version="1 ...

  2. Struts2 校验框架学习笔记

    Struts2 校验框架 Struts2 和Struts1同样也提供了校验框架,但在Struts2 已经不再把校验框架做为一个插件,而是已经内置到了Struts2中,而且配置起来更为简单方便,功能也更 ...

  3. Struts2校验

    struts2校验有两种实现方法: 手工编写代码实现(基本验证) //login.jsp <font color="red"><s:fielderror/> ...

  4. struts2 校验数据的有效性 2种方式

    Struts2的数据校验: 数据的校验分为客户端校验和服务器端两种: 客户端校验:JS完成的校验.(为了提升用户体验.减少用户的输入错误) 服务器端校验:在后台的校验.(必须的.) 手动编码进行校验: ...

  5. struts2校验の实现

    1.JSP <%@ page contentType="text/html; charset=utf-8" language="java" errorPa ...

  6. struts2校验器规范错误解决

    今天struts2的校验器的配置文件文件头出现了错误,配置如下: <!DOCTYPE validators PUBLIC        "-//OpenSymphony Group// ...

  7. 使用 Struts2 校验器校验用户注册信息

    基于验证框架的输入校验 一.创建一个struts2项目testValidators.Struts2 初体验:http://www.cnblogs.com/likailan/p/3280820.html ...

  8. 使用 Struts2 校验器校验用户注册信息的例子

    转自:https://blog.csdn.net/jin2005006/article/details/53999562 基于验证框架的输入校验 一.创建一个struts2项目testValidato ...

  9. struts2 校验demo

    综合练习: <validators> <field name="username"> <field-validator type="requ ...

随机推荐

  1. ubuntu中安装VMWare tools

    在进入VMware Workstation之后找到虚拟机然后选择安装VMWare Tools 在下载的安装包中找到linux.iso,比如我的是C:\Program Files (x86)\VMwar ...

  2. oracle数据泵实现不同用户之间的导出导入

    来源于:http://www.cnblogs.com/kevinsun/archive/2007/02/03/638803.aspx http://blog.sina.com.cn/s/blog_68 ...

  3. Elasticsearch: Indexing SQL databases. The easy way

    Elasticsearchis a great search engine, flexible, fast and fun. So how can I get started with it? Thi ...

  4. 编译php5.4的时候出现错误----configure: error: in `/usr/local/src/php540/php-5.4.0':

    错误如下:checking for grep that handles long lines and -e... /bin/grep checking for egrep... /bin/grep - ...

  5. javaweb学习总结(四十二)——Filter(过滤器)学习

    一.Filter简介 Filter也称之为过滤器,它是Servlet技术中最激动人心的技术,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态 ...

  6. 控件 UI: VisualState, VisualStateManager, 控件的默认 UI

    VisualState 和 VisualStateManager 控件的默认 Style, ControlTemplate, VisualState 示例1.演示“VisualState 和 Visu ...

  7. BIEE报表开发

    (1)报表开发实例结果图 (2)开发报表步骤: (1)创建分析 (2)创建仪表盘提示 (3)创建仪表盘并发布 登录网址,输入用户名和密码 1) 新建——>分析——>选择主题区域——> ...

  8. ml的线性回归应用(python语言)

    线性回归的模型是:y=theta0*x+theta1   其中theta0,theta1是我们希望得到的系数和截距. 下面是代码实例: 1. 用自定义数据来看看格式: # -*- coding:utf ...

  9. Leetcode 226. Invert Binary Tree

    Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 class Solution(object): ...

  10. Leetcode 134 Gas Station

    There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...