1. 程式人生 > >Struts2 短路驗證&非欄位驗證

Struts2 短路驗證&非欄位驗證

短路驗證

若一個欄位有多個驗證器的話,預設情況下會執行所有的驗證器,若希望前面的驗證器沒有通過的話,後面就不再驗證,可以使用短路驗證。

<validator/>元素和<field-validator/>元素可以指定一個可選的short-circuit屬性,該屬性指定驗證器是否為短驗證器,預設為false

<!DOCTYPE validators PUBLIC
        "-//Apache Struts//XWork Validator 1.0.2//EN"
        "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>
   <!--  針對age屬性進行驗證-->
   <field name="age">
   <!-- 型別轉換問題 -->
   <!-- 短路驗證,如果當前驗證沒有通過的話,就不會進行下面的驗證 -->
   <field-validator type="conversion" short-circuit="true">
   <message>Conversion Error Occurred</message>
   </field-validator>
   <!-- -欄位範圍內 -->
   <field-validator type="int">
   <param name="min">20</param>
   <param name="max">50</param>
   <message key="error_age"></message>
   </field-validator>
   </field>
</validators>

若型別轉化失敗,預設情況下還會執行後面的攔截器,還會進行驗證。

可以通過修改ConversionErrorInterceptor原始碼的方式使當型別轉換失敗時,不再執行後續的驗證攔截器,而直接返回input的result


 非欄位驗證(密碼與確認密碼的功能)

非欄位驗證:不是針對某一個欄位的驗證,例如密碼與確認密碼兩個欄位的比較

demo如下

Action類

package cn.com.app;
import com.opensymphony.xwork2.ActionSupport;
public class TextValidation extends ActionSupport {
	private static final long serialVersionUID = 1L;
	/*
	 * author:命運的信徒 date:2018/12/17 arm:申明式的驗證
	 */
	private int age;
	private String password;
	private String password2;
	
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getPassword2() {
		return password2;
	}
	public void setPassword2(String password2) {
		this.password2 = password2;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String execute() {
		System.out.println("age:" + age);
		return SUCCESS;
	}
}

 申明式驗證的配置

 

<!DOCTYPE validators PUBLIC
        "-//Apache Struts//XWork Validator 1.0.2//EN"
        "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>
	<!-- 針對age屬性進行驗證 -->
	<field name="age">
		<!-- 型別轉換問題 -->
		<!-- 短路驗證,如果當前驗證沒有通過的話,就不會進行下面的驗證 -->
		<field-validator type="conversion" short-circuit="true">
			<message>Conversion Error Occurred</message>
		</field-validator>
		<!-- -欄位範圍內 -->
		<field-validator type="int">
			<param name="min">20</param>
			<param name="max">50</param>
			<message key="error_age"></message>
		</field-validator>
	</field>


	<!-- 非欄位驗證 -->
	<validator type="expression">
		<param name="expression"><![CDATA[password=password2]]></param>
		<message> password is not equals password2</message>

	</validator>

</validators>




struts.xml

<action name="mag" class="cn.com.app.TextValidation">
<result name="input">/validator.jsp</result>
<result>/success.jsp</result>
</action>

jsp頁面

<body>
<s:actionerror/>
	<s:form action="mag.action">
		<s:textfield name="age" label="age"></s:textfield>
		<s:password name="password" label="password"></s:password>
		<s:password name="password2" label="password2"></s:password>
		<s:submit></s:submit>
	</s:form>
</body>

非欄位驗證在頁面上顯示

<s:actionerror/>