表单数据的验证:
前台验证:主要是通过JS验证, 表达数据是否合法!
后台验证:通过后台java代码进行验证!
Struts也提供了数据效验的方式!
Struts数据效验, 通过拦截器完成:
<interceptor name="validation" class="org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor"/>
代码方式验证Action中所有的方法:
步骤:
1. 搭建struts环境
2. login.jsp
3.UserAction.java
Struts数据效验错误信息处理:
public synchronized void addFieldError(String fieldName, String errorMessage) { // 1. 保存错误信息的map集合 final Map<String, List<String>> errors = internalGetFieldErrors(); // 2. Map的value值 (一个key,对应的多个值用list存储) List<String> thisFieldErrors = errors.get(fieldName); // 3. 如果错误信息的map中没有当前的key,就直接创建集合 if (thisFieldErrors == null) { // 创建 thisFieldErrors = new ArrayList<String>(); errors.put(fieldName, thisFieldErrors); } // 4. 添加错误信息 thisFieldErrors.add(errorMessage); }
Action实现:
import com.opensymphony.xwork2.ActionSupport; /** * 注意:如果要想用struts的数据效验功能,必须继承ActionSupport或实现相关接口 * */ public class UserAction extends ActionSupport { // 封装请求数据 private User user = new User(); public void setUser(User user) { this.user = user; } public User getUser() { return user; } /* // 重写数据验证的方法 public void validateRegister() { // 用户名非空 if (user.getUserName() == null || "".equals(user.getUserName())) { // 保存错误信息 super.addFieldError("userName", "用户名必须填写!"); } // 密码 if (user.getPwd() == null || "".equals(user.getPwd())) { super.addFieldError("pwd", "密码必填"); } } */ @Override public void validate() { // 用户名非空 if (user.getUserName() == null || "".equals(user.getUserName())) { // 保存错误信息 super.addFieldError("userName", "用户名必须填写!"); } // 密码 if (user.getPwd() == null || "".equals(user.getPwd())) { super.addFieldError("pwd", "密码必填"); } } // 业务方法 public String register() { System.out.println(user); System.out.println(1); return SUCCESS; } // 列表展示(不用数据效验) public String list() { return SUCCESS; } }
代码方式验证Action中指定的方法:
写验证方法命名规则:
validate + 要验证的方法名
如:
public void validateRegister() {
只会验证当前action的register方法!
XML方式验证Action中所有的方法:
总结代码方式验证:
繁琐,设计很多重复的验证逻辑!例如:非空验证、数值验证、email、日期等。
Struts对于常用的验证,进行了封装,即提供了验证器, 验证指定的常用业务逻辑!
Struts提供的所有验证器:
路径:xwork-core-2.3.4.1.jar/com.opensymphony.xwork2.validator.validators/default.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"> <!-- START SNIPPET: validators-default --> <validators> <validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/> <validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/> <validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/> <validator name="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/> <validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/> <validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/> <validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/> <validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/> <validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/> <validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/> <validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/> <validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/> <validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/> <validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/> <validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/> <validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/> </validators> <!-- END SNIPPET: validators-default -->
如果写xml,从而定义验证规则:
1)XML文件名称语法: ActionClassName-validation.xml
注意:此xml需要与当期要验证的action在同一个目录:
举例:UserAction-validation.xml
2) 写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表示 --> <field name="user.userName"> <!-- 指定使用的验证器 --> <field-validator type="requiredstring"> <!-- 验证失败的错误提示信息 --> <message>用户名不能为空!</message> </field-validator> </field> <!-- 验证pwd --> <field name="user.pwd"> <!-- 非空 --> <field-validator type="requiredstring"> <message>密码不能为空!</message> </field-validator> <!-- 长度 --> <field-validator type="stringlength"> <param name="minLength">6</param> <param name="maxLength">8</param> <message>密码必须为6-8位~~~~</message> </field-validator> </field> <!-- 验证日期 --> <field name="user.birth"> <field-validator type="date"> <message>日期格式不对!</message> </field-validator> </field> <!-- 验证Email --> <field name="user.email"> <field-validator type="email"> <message>邮箱格式错误!</message> </field-validator> </field> </validators>
XML方式验证Action中指定的方法:
与上面xml验证方式大致相同: 验证xml文件内容不变;
文件命名:
语法:ActionClassName-ActionName-validation.xml
举例:UserAction-user_register-validation.xml
验证UserAction中的register方法
验证总结
代码:
重写validate() , 验证action所有方法
Validate方法名(), 验证指定“方法名”的方法
Xml:
验证所有方法: ActionClassName-validation.xml
验证指定方法: ActionClassName-actionName-validation.xml
代码验证,
比较灵活,可以满足所有的需求.
比较繁琐,要写重复的验证判断逻辑!
适合: 表单字段较少的情况用!
XML验证:
通用,但不够灵活; 可以验证特定简单的业务。
适合: 验证表单字段较多,可以大大简化代码!
(配置文件过多)
验证错误处理
Struts在进行数据效验的时候,验证失败,会返回input视图,要求我们要在struts.xml中配置input视图对应的错误页面!
配置: Struts.xml <!-- 注册失败跳转到注册页面,显示失败信息 --> <global-results> <result name="input">/register.jsp</result> </global-results>
Jsp显示错误
方式1:显示所有错误 <%@taglib uri="/struts-tags" prefix="s" %> <!-- 显示的是struts在运行时期产生的所有错误 --> <s:fielderror></s:fielderror> 方式2:显示指定的错误 <!-- 修改struts标签默认的样式: 不让换行 --> <style type="text/css"> ul{ display: inline; } ul li{ display: inline; color: red; } </style> 显示指定的错误: <s:fielderror fieldName="user.userName"></s:fielderror> 方式3: 修改标签定义的模板 找到fielderror标签定义的模板文件: Struts-core.jar emplatesimple fielderror.ftl 把修改后的fielderror.ftl文件,放到src/ template/ simple/ fielderror.ftl 这样标签显示的样式就修改了!
fielderror.ftl
<#-- /* * $Id: fielderror.ftl 805635 2009-08-19 00:18:54Z musachy $ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ --> <#if fieldErrors??><#t/> <#assign eKeys = fieldErrors.keySet()><#t/> <#assign eKeysSize = eKeys.size()><#t/> <#assign doneStartUlTag=false><#t/> <#assign doneEndUlTag=false><#t/> <#assign haveMatchedErrorField=false><#t/> <#if (fieldErrorFieldNames?size > 0) ><#t/> <#list fieldErrorFieldNames as fieldErrorFieldName><#t/> <#list eKeys as eKey><#t/> <#if (eKey = fieldErrorFieldName)><#t/> <#assign haveMatchedErrorField=true><#t/> <#assign eValue = fieldErrors[fieldErrorFieldName]><#t/> <#if (haveMatchedErrorField && (!doneStartUlTag))><#t/> <#assign doneStartUlTag=true><#t/> </#if><#t/> <#list eValue as eEachValue><#t/> ${eEachValue} </#list><#t/> </#if><#t/> </#list><#t/> </#list><#t/> <#if (haveMatchedErrorField && (!doneEndUlTag))><#t/> <#assign doneEndUlTag=true><#t/> </#if><#t/> <#else><#t/> <#if (eKeysSize > 0)><#t/> <ul<#rt/> <#if parameters.cssClass??> class="${parameters.cssClass?html}"<#rt/> <#else> class="errorMessage"<#rt/> </#if> <#if parameters.cssStyle??> style="${parameters.cssStyle?html}"<#rt/> </#if> > <#list eKeys as eKey><#t/> <#assign eValue = fieldErrors[eKey]><#t/> <#list eValue as eEachValue><#t/> <li><span><#if parameters.escape>${eEachValue!?html}<#else>${eEachValue!}</#if></span></li> </#list><#t/> </#list><#t/> </ul> </#if><#t/> </#if><#t/> </#if><#t/>