struts2对action中的方法进行输入校验---xml配置方式(3)

上面两篇文章已经介绍了通过编码java代码的方式实现action方法校验,这里我们介绍另外一种方式:xml配置文件

首先我们来看一个例子:

ValidateAction.java:

package com.itheima.action;

import com.opensymphony.xwork2.ActionSupport;

public class ValidateAction extends ActionSupport {

	private String username;
	private String tel;
	private String msg;

	public void setUsername(String username) {
		this.username = username;
	}

	public void setTel(String tel) {
		this.tel = tel;
	}

	public String getUsername() {
		return username;
	}

	public String getTel() {
		return tel;
	}

	public String getMsg() {
		return msg;
	}

	public String execute1() {
		msg = "execute1";
		return "success";
	}

	public String execute2() {
		msg = "execute2";
		return "success";
	}
}

这里大家也看到了在该action中我们并没有重写validate方法。但是需要注意的是,通过配置xml文件这时就需要添加getXXX方法,不然框架获取不到字段的值

struts2.xml:

<action name="validateAction_*" class="com.itheima.action.ValidateAction" method="{1}">
	<result name="success">/success.jsp</result>
	<result name="input">/person.jsp</result>
</action>

person.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!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:fielderror/>
	<form action="${pageContext.request.contextPath }/validateAction_execute1.action" method="post">
		用户名:<input type="text" name="username"><br>
		手机号:<input type="text" name="tel"><br>
		<input type="submit" value="提交">
	</form>
</body>
</html>

success.jsp:

<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
	${msg }
</body>
</html>

然后我们配置xml文件:

首先需要将xml文件配置在需要校验的action所在的包下(同包),然后文件名有个严格的格式:ActionClassName-validation.xml

其中ActionClassName为校验的action名称,-validation.xml部分固定不变。

本例中为ValidateAction-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="username">
        <field-validator type="requiredstring">
        	<param name="trim">true</param>
            <message>用户名不能为空。。。</message>
        </field-validator>
    </field>
    <field name="tel">
        <field-validator type="requiredstring">
            <message>手机号不能为空。。。</message>
        </field-validator>
       	<field-validator type="regex">
       		<param name="regexExpression"><![CDATA[^1[358]\d{9}$]]></param>
       		<message>手机号格式不正确。。。</message>
       	</field-validator>
    </field>
</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

下面是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>

(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

(6)还有一个需要注意的地方是:

ValidateAction-validation.xml文件引用的dtd文件来自网络,也就是说如果电脑没有联网,编辑该文件时按住alt+/就不会自动提示,所以我们这里可以这么做:

ValidateAction-validation.xml文件顶部有如下内容:

<!DOCTYPE validators PUBLIC

"-//Apache Struts//XWork Validator 1.0.3//EN"

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

即:<!DOCTYPE 根标签名 public   dtd名称  dtdurl地址>,public代表引用网络资源

我这里以eclipse做说明:

windows/preferences/xml/xml  catalog

然后打开如下对话框:

点击add,出现如下窗口

点击system file,然后选择上述路径下的xwork-validator-1.0.3.dtd文件,然后在key type下拉框中选择URI选项

在key输入框中输入引用的网络dtd文件的网络位置,这里为:http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd,然后保存就ok了

时间: 2024-08-12 22:04:03

struts2对action中的方法进行输入校验---xml配置方式(3)的相关文章

struts2对action中的方法进行输入校验

有时我们需要对Action中注入的字段进行校验,这时我们就需要用到invidate()方法了. 首先需要Action实现ActionSupport,然后重写invidate()方法,在其中对字段进行校验. 如果校验合法,则执行action中的相应方法(一般为execute),请求转发到相应的jsp: 如果校验失败,可以通过addFieldError()方法将错误信息添加到FieldErrors中, 此时action中的相应方法(一般为execute)不会执行,struts2框架默认返回"inpu

struts2对action中的方法进行输入校验(2)

struts2输入校验流程: 1.类型转换器对请求参数执行类型转换,并把转换后的值赋给aciton中的属性 2.如果在执行类型转换的过程中出现异常,系统会将异常信息保存到ActionContext, conversionError拦截器将异常信息添加到fieldErrors里,不管类型转换是否出现异常,都会进入第三步 3.系统通过反射技术先调用action的validateXXX方法 4.再调用aciton中的validate方法 5.经过上述的4步,如果系统中的fieldErrors存在错误信

转载 - Struts2基于XML配置方式实现对action的所有方法进行输入校验

出处:http://www.cnblogs.com/Laupaul/archive/2012/03/15/2398360.html 使用基于XML配置方式实现输入校验时,Action也需要继承ActionSupport,并且提供校验文件,校验文件和action类放在同一个包下,文件的取名格式为:ActionClassName-validation.xml.ActionClassName为action的简单类名,-validation为固定写法.如果Action类为cn.validate.acti

第三章Struts2 Action中动态方法调用、通配符的使用

01.Struts 2基本结构 使用Struts2框架实现用登录的功能,使用struts2标签和ognl表达式简化了试图的开发,并且利用struts2提供的特性对输入的数据进行验证,以及访问ServletAPI时实现用户会话跟踪,其简单的程序运行流程图如下 Struts2框架是基于MVC模式.基于MVC模式框架的核心就是控制器对所有请求进行统一处理.Struts2的控制器StrutsPrepareAndExecuteFilter由ServletAPI中的Filter充当,当web容器的接收到登录

【JAVA学习】struts2的action中使用session的方法

尊重版权:http://hi.baidu.com/dillisbest/item/0bdc35c0b477b853ad00efac 在Struts2里,如果需要在Action中使用session,可以通过下面两种方式得到1.通过ActionContext class中的方法getSession得到2.Action实现org.apache.struts2.interceptor.SessionAware接口的方式来对session进行操作 下面先看一个采用第一种方式,在action中得到sessi

struts2学习笔记(4)---------action中的方法调用

系统需要使用Action的不同方法来处理用户请求,这就需要让同一个Action里面包含多个控制处理逻辑. 1)动态方法调用 即DMI(dynamic method invocation),使用actionName!methodName的形式来指定想要调用的方法,如果想使用DMI,需要在struts.xml里面加入这句话: <constant name="struts.enable.DynamicMethodInvocation" value="true" /&

Struts2 的Action中取得请求参数值的几种方法

Struts2 的Action中取得请求参数值的几种方法 先看GetRequestParameterAction类代码: Java代码 public class GetRequestParameterAction extends ActionSupport { private String bookName; private String bookPrice; public String getBookName() { return bookName; } public void setBook

Struts2 Action中动态方法调用、通配符的使用

一.Struts2执行过程图: 二.struts2配置文件的加载顺序 struts-default.xml---struts-plugin.xml---struts.xml 具体步骤: 三.Action中动态方法调用<Dynamic Method Invocation> DMI 第一种方式: 自定义DMIAction类,使它继承ActionSupport类,该类无需手动重写execute(),底层有默认实现.因此我们也可以自定义方法list. struts.xml中的action元素植入met

Action中动态方法的调用 Action中通配符的使用 Result的配置

   Action中动态方法的调用 动态方法调用(Dynamic Method Invocation,DMI) 标识符:! 一.通过以下选中的文件来查看是否禁止调用动态方法 二.在我们自定义的action类中,我们不再单一的继承来自父类的方法,我们可以自定义自己的方法 1 package cn.jbit.booklist; 2 3 import com.opensymphony.xwork2.ActionSupport; 4 5 public class BookList extends Act