---
title: "struts1.2验证框架入门"
author: "yunchow"
date: "2009-09-20T23:52:31Z"
tags: ["Bean", "Struts", "XML", "框架", "正则表达式"]
slug: "struts1-2"
draft: false
lastmod: "2009-09-21T00:15:45Z"
id: 472826
url: "https://yunchow.iteye.com/blog/472826"
---

Struts 验证 在ActionForm里的validate方法里主要进行页面格式的验证 而在Action中进行业务方面验证. \[code="java"]ActionErrors validate() { ActionErrors errors = new ActionErrors(); errors.add(String/\*与页面的出错标签相对应\*/, new ActionMessage("errors.username"/\*和资源文件里的Key对应\*/));\[/code] } 在资源文件中有两个特殊的属性,它们会自动加到消息的头部和尾部. errors.header= errors.footer= 但是要注意:在资源文件中写JS脚本是不对的. errors.header= 这样写是没办法解析的.可采用如下手段进行Script的解析. \[code="java"] errors.add("user", new ActionMessage("不允许不空", false)); //ActionErrors errors = new ActionErrors(); //errors.add(ActionErrors.GLOBAL\_MESSAGE, new ActionMessage("密码不正确", false)); //saveErrors(request, errors); // 保存errors ActionMessage msgs = new ActionMessage(); msgs.add(ActionMessage.GLOBAL\_MESSAGE, new ActionMessage("密码不正确", false)); //saveMessage(request, msgs); saveErrors(request, msgs);\[/code] ${msg} --------------------------------------- Validate 验证框架 通过xml配置来实现验证工作 validator-rules.xml 要验证的Form要继承ValidatorForm. 在validation.xml中

`minlength 6``mask ^[a-z0-9A-Z]*$`

---------------------------- 正则表达式: \\s 空格 \\S 非空格 \\d 数字 \\D 非数字 \\w 单词 \\W 非单词 ^ 一行的开始 $ 一行结尾 ? 0个或1个 * 0个或多个 + 一个或多个 {n} n个 --------------- 自定义规则: \[code="java"]public class SelValidator { public static boolean validateMinSel( Object bean, ValidatorAction va, Field field, ActionMessage message, Validator validator, HttpServletRequest request) { // 把interest数组取出来 // 把minSel到底最少要取几个的数字取出来 // 比较 // 如果验证不成功,要生成错误消息. String propName = field.getProperty(); // String\[] interests = request.getParameterValues(propName); try { String\[] interests = (String\[])PropertyUtils.getProperty(bean, propName); Integer minSel = new Integer(field.getVarValue("min")); if(interests.length &gt;= minSel) return true; else { if(messages==null) messages = new ActionMessages(); messags.add(,field.getProperty()/\*等同field.getKey()\*/ Resources.getActionMessage(validator,request,va,field)); return false; } } catch(Exception ex){ if(messages==null) messages = new ActionMessages(); messags.add(,field.getProperty()/\*等同field.getKey()\*/ Resources.getActionMessage(validator,request,va,field)); return false; } } }\[/code] ---------------------------------------------------- ValidatorActionForm DynaValidatorActionForm // 它们是根据Action的path来验证的. 这是与ValidatorForm的惟一的区别． --------------------------------------- Struts 国际化. ApplicationResource\_zh\_CN.properties ApplicationResource\_en\_US.properties ApplicationResource.properties native2ascii命令用法: native2ascii -encoding GBK tmp.properties ApplicationResource\_zh\_CN.properties 验证转码是否成功: 在浏览器中修改显示语言. --------------------------------- 验证框架总结: 1, ActionForm要继承ValidatorForm或ValidatorActionForm 2, struts-config.xml中加 3, 加validator-rules.xml中的消息copy到资源文件中 4, 新建validation.xml, 在WEB-INF下,把validator-rules.xml中的DTD考过来 5,