自定义拦截器的步骤:
1、定义一个验证器的类:
> 自定义的验证器都需要实现 Validator接口.
> 可以选择继承 ValidatorSupport 或 FieldValidatorSupport 类,这两个类都实现了Validator接口了;FieldValidatorSupport继承ValidatorSupport,FieldValidatorSupport用于 字段验证
> 若希望实现一个一般的验证器, 则可以继承 ValidatorSupport
> 若希望实现一个字段验证器, 则可以继承 FieldValidatorSupport
> 具体实现可以参考目前已经有的验证器. 例如:RequiredFieldValidator验证器
> 若验证程序需要接受一个输入参数, 需要为这个参数增加一个相应的属性
代码实现如下:
IDCard.java
package com.lym.struts2.validation.app; public class IDCard { final int[] wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 }; final int[] vi = { 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 }; private int[] ai = new int[18]; public IDCard() {} public boolean Verify(String idcard) { if (idcard.length() == 15) { idcard = uptoeighteen(idcard); } if (idcard.length() != 18) { return false; } String verify = idcard.substring(17, 18); if (verify.equals(getVerify(idcard))) { return true; } return false; } public String getVerify(String eightcardid) { int remaining = 0; if (eightcardid.length() == 18) { eightcardid = eightcardid.substring(0, 17); } if (eightcardid.length() == 17) { int sum = 0; for (int i = 0; i < 17; i++) { String k = eightcardid.substring(i, i + 1); ai[i] = Integer.parseInt(k); } for (int i = 0; i < 17; i++) { sum = sum + wi[i] * ai[i]; } remaining = sum % 11; } return remaining == 2 ? "X" : String.valueOf(vi[remaining]); } public String uptoeighteen(String fifteencardid) { String eightcardid = fifteencardid.substring(0, 6); eightcardid = eightcardid + "19"; eightcardid = eightcardid + fifteencardid.substring(6, 15); eightcardid = eightcardid + getVerify(eightcardid); return eightcardid; } public static void main(String[] args) { String idcard1 = "231003199409032635"; String idcard2 = "350211197607442059"; IDCard idcard = new IDCard(); System.out.println(idcard.Verify(idcard1)); System.out.println(idcard.Verify(idcard2)); } }2、在配置文件中配置验证器
> 默认情况下, Struts2 会在 类路径的根目录下加载 validators.xml 文件. 在该文件中加载验证器.
该文件的定义方式同默认的验证器的那个配置文件: 位于 com.opensymphony.xwork2.validator.validators 下的 default.xml
> 若类路径下没有指定的验证器, 则从 com.opensymphony.xwork2.validator.validators 下的 default.xml 中的验证器加载
所以,需要在src目录下定义一个validators.xml 文件
代码实现如下:
validators.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator Definition 1.0//EN" "http://struts.apache.org/dtds/xwork-validator-definition-1.0.dtd"> <!-- 自定义身份证号验证拦截器 --> <validators> <validator name="idCard" class="com.lym.struts2.validation.app.IDCardValidator"/> </validators>
3、使用自定义验证器,方法同使用其他的验证器一样
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd"> <validators> <!-- 省份证号验证拦截器测试 --> <field name="idCard"> <field-validator type="idCard" short-circuit="true"> <message key="error.idCard"></message> </field-validator> </field> </validators>
以下是工程文件截图: