SimpleAction-validation.xml 名字前綴要與類名相同,而且與之在同一目錄下<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN" "
<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>