Struts2的自定義校驗規則
1、自定義校驗器
若需要字段驗證程序,可以繼承FiledValidatorSupport類
針對一個字段的校驗(例如:用戶名)
a、JSP文件
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:fielderror></s:fielderror>
<h1>自定義的校驗器</h1>
<form action="${ pageContext.request.contextPath }/regist2.action" method="post">
年齡:<input type="text" name="age"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
b、RegistAction2
package com.itzheng.web.action.demo6;
import com.opensymphony.xwork2.ActionSupport;
public class RegistAction2 extends ActionSupport {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return NONE;
}
}
c、struts.xml
d、MyAgeVaildator繼承ValidatorSupport類
package com.itzheng.web.action.demo6;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
/*
* 自定義的校驗規則
*/
public class MyAgeVaildator extends FieldValidatorSupport {
@Override
public void validate(Object obj) throws ValidationException {
// 獲得字段名稱:
String name = this.getFieldName();
//獲得字段的值
Object value = this.getFieldValue(name, obj);//得到文本框當中的值
//instanceof用來測試一個對象是否爲一個類的實例,
if(value instanceof Integer) {//判斷value是否是Integer的實現類
int age = (Integer)value;
if(age < 0) {
this.addFieldError(name, obj);
}
}
}
}
e、在src下創建validators.xml:註冊校驗規則
需要找到頭文件,在xwork-core-2.3.7.jar下的xwork-validator-config-1.0.dtd
引入頭文件,創建自定義校驗的文件validators.xml在src下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator Config 1.0//EN"
"http://struts.apache.org/dtds/xwork-validator-config-1.0.dtd">
<validators>
<validator name="age" class="com.itzheng.web.action.demo6.MyAgeVaildator">
</validator>
</validators>
f、使用上面創建好的校驗規則,創建XML,設置要校驗的信息
在和要校驗信息類同包下創建RegistAction2-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="age">
<!-- 校驗規則 -->
<!-- type當中的必須和validators當中validator name="age"名稱一樣 -->
<field-validator type="age">
<!-- 錯誤信息 -->
<message>年齡不能爲負數!</message>
</field-validator>
</field>
</validators>
測試