SimpleAction-validation.xml 名字前缀要与类名相同,而且与之在同一目录下<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN" "
http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">
<validators>
<field name="count">
<field-validator type="required">
<message>You must enter a value for count.</message>
</field-validator>
<field-validator type="int">
<param name="min">0</param>
<param name="max">5</param>
<message>
count must be between ${min} and ${max}, current value is ${count}.
</message>
</field-validator>
</field>
</validators>
==
package helloWorld;
import com.opensymphony.xwork.ActionSupport;
import com.opensymphony.xwork.ValidationAware;
public String doExecute() throws Exception {
return SUCCESS;
}
}
------
在xwork.xml里面添加
<interceptors>
<interceptor name="validator" class="com.opensymphony.xwork.validator.ValidationInterceptor"/>
</interceptors>
<action name="validation" class="helloWorld.SimpleAction">
<result name="success" type="dispatcher">
<param name="location">/simple_result.jsp</param>
</result>
<result name="error" type="dispatcher">
<param name="location">/simple.jsp</param>
</result>
<!-- If you don't override execute(), you must do this: -->
<result name="input" type="dispatcher">
<param name="location">/simple.jsp</param>
</result>
<interceptor-ref name="validator" />
<interceptor-ref name="debugStack" />
<interceptor-ref name="defaultStack" />
</action>
注意interceptor为多个时与servlet里面的filter一样按顺序依次传递,假若失败就为影响后面的程序运行效果.
还有两个jsp页面
simple_result.jsp
<%@ taglib prefix="ww" uri="webwork"%>
<html>
<head>
<title>WebWork Validation Example</title>
</head>
<body>
<p>
The count is
<ww:property value="count" />
</p>
</form>
</body>
</html>
--
simple.jsp
<%@ taglib prefix="ui" uri="webwork" %>
<html>
<head>
<title>WebWork Validation Example</title>
</head>
<body>
<form action="validation.action" method="post">
<table>
<ui:textfield label="Set the counter" name="count"/>
<ui:submit value="'Submit'"/>
</table>
</form>
</body>
</html>
运行效果如下
下面为日期类型的验证
<field-validator type="date">
<param name="min">12/22/2002</param>
<param name="max">12/25/2002</param>
<message>The date must be between 12-22-2002 and 12-25-2002.</message>
</field-validator>
</field>
<field name="foo">
<field-validator type="int">
<param name="min">0</param>
<param name="max">100</param>
<message key="foo.range">Could not find foo.range!</message>
</field-validator>
</field>
</validators>