一脸懵逼学习Struts数据校验,数据回显,模型驱动,防止表单重复提交。
Posted --->别先生<---
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一脸懵逼学习Struts数据校验,数据回显,模型驱动,防止表单重复提交。相关的知识,希望对你有一定的参考价值。
1:Struts2表单数据校验:
(1)前台校验,也称之为客户端校验,主要是通过javascript编程的方式进行数据的验证。
(2)后台校验,也称之为服务器校验,这里指的是使用Struts2通过xml配置的方式进行表单数据的校验。
(3)代码方式验证Action中所有的方法;代码方式验证Action中指定的方法;xml方式验证Action中所有的方法;xml方式验证Action中指定的方法;
2:代码方式验证Action中所有的方法(自己记得导jar包和我配置web.xml文件,自己脑补吧):
注册的jsp页面:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>数据校验</title> 8 </head> 9 <body> 10 11 <form action="${pageContext.request.contextPath}/data_checkData.action" method="post"> 12 账号:<input type="text" name="user.name"/><br/> 13 密码:<input type="password" name="user.password"/><br/> 14 邮箱:<input type="text" name="user.email"/><br/> 15 生日:<input type="text" name="user.birthday"/><br/> 16 17 <input type="submit" value="注册"/> 18 <input type="reset" value="重置"/> 19 </form> 20 21 </body> 22 </html>
数据校验的Action类的实现:
1 package com.bie.lesson10; 2 3 import com.opensymphony.xwork2.ActionSupport; 4 5 /** 6 * @author Author:别先生 7 * @date Date:2017年9月24日 下午3:28:25 8 * 9 * 1:注意,如果想要用struts的数据校验功能,必须继承ActionSupport或者实现相关接口; 10 */ 11 public class CheckAction extends ActionSupport{ 12 13 /** 14 * 15 */ 16 private static final long serialVersionUID = 1L; 17 18 //封装请求数据 19 private User user; 20 public void setUser(User user) { 21 this.user = user; 22 } 23 public User getUser() { 24 return user; 25 } 26 27 //重写数据校验的功能 28 @Override 29 public void validate() { 30 //用户名非空校验 31 if(user.getName() == null || "".equals(user.getName())){ 32 //保存错误信息 33 super.addFieldError("name", "用户的账号不能为空。"); 34 } 35 //密码非空校验 36 if(user.getPassword() == null || "".equals(user.getPassword())){ 37 //保存错误信息 38 super.addFieldError("password", "用户的密码不能为空"); 39 } 40 //用户的邮箱校验 41 /*if(user.getEmail() == null || "".equals(user.getEmail())){ 42 //保存错误信息 43 super.addFieldError("email", "用户的邮箱不能为空"); 44 }*/ 45 //用户的生日不能为空 46 /*if(user.getBirthday() == null || "".equals(user.getBirthday())){ 47 //保存错误信息 48 super.addFieldError("birthday" , "用户的生日不能为空"); 49 }*/ 50 51 } 52 53 //业务方法 54 public String checkData(){ 55 56 System.out.println(user); 57 return SUCCESS; 58 } 59 60 }
struts2的配置xml文件:
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 4 "http://struts.apache.org/dtds/struts-2.0.dtd"> 5 6 <struts> 7 <package name="checkPackage" extends="struts-default"> 8 <action name="data_*" class="com.bie.lesson10.CheckAction" method="{1}"> 9 <result name="success">success2.jsp</result> 10 <result name="input">error.jsp</result> 11 </action> 12 13 </package> 14 15 </struts> 16
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 4 "http://struts.apache.org/dtds/struts-2.0.dtd"> 5 6 <struts> 7 <!-- struts在允许的时候会加载这个总配置文件:src/struts.xml --> 8 9 <!-- 全局配置 --> 10 <!-- 修改Struts的默认访问后缀 --> 11 <!-- <constant name="struts.action.extension" value="action,do,struts,"></constant> --> 12 <include file="constant.xml"></include> 13 14 <!-- 在总配置文件中引入其他所有的配置文件 --> 15 16 <!-- <include file="com/bie/lesson/helloStruts.xml"></include> --> 17 18 <!-- <include file="com/bie/lesson02/strutsAction.xml"></include> --> 19 20 <!-- <include file="com/bie/lesson03/strutsConfig.xml"></include> --> 21 22 <!-- <include file="com/bie/lesson04/strutsData.xml"></include> --> 23 24 <!-- <include file="com/bie/lesson05/strutsType.xml"></include> --> 25 26 <!-- <include file="com/bie/lesson06/strutsUpload.xml"></include> --> 27 28 <!-- <include file="com/bie/lesson07/strutsInterceptor.xml"></include> --> 29 30 <!-- <include file="com/bie/lesson08/action/strutsAdmin.xml"></include> --> 31 32 <!-- <include file="com/bie/lesson09/strutsOgnl.xml"></include> --> 33 34 <include file="com/bie/lesson10/strutsCheck.xml"></include> 35 36 37 38 39 </struts>
用户的实体类的内容:
1 package com.bie.lesson10; 2 3 import java.util.Date; 4 5 /** 6 * @author Author:别先生 7 * @date Date:2017年9月24日 下午3:59:21 8 * 9 * 10 */ 11 public class User { 12 13 private String name; 14 private String password; 15 private String email; 16 private Date birthday; 17 public String getName() { 18 return name; 19 } 20 public void setName(String name) { 21 this.name = name; 22 } 23 public String getPassword() { 24 return password; 25 } 26 public void setPassword(String password) { 27 this.password = password; 28 } 29 public String getEmail() { 30 return email; 31 } 32 public void setEmail(String email) { 33 this.email = email; 34 } 35 public Date getBirthday() { 36 return birthday; 37 } 38 public void setBirthday(Date birthday) { 39 this.birthday = birthday; 40 } 41 public User(String name, String password, String email, Date birthday) { 42 super(); 43 this.name = name; 44 this.password = password; 45 this.email = email; 46 this.birthday = birthday; 47 } 48 public User() { 49 super(); 50 } 51 52 53 }
成功的页面和失败的页面:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ taglib prefix="s" uri="/struts-tags"%> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>struts2 hello </title> 9 </head> 10 <body> 11 12 <h1>成功注册</h1> 13 14 15 16 <!-- struts的调试标签:可以观测值栈数据 --> 17 <s:debug></s:debug> 18 </body> 19 </html>
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ taglib uri="/struts-tags" prefix="s"%> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>Insert title here</title> 9 </head> 10 <body> 11 12 <h1>错误的视图</h1> 13 <h1>错误的error</h1> 14 15 <!-- 查看struts框架在运行时期产生的所有错误信息 --> 16 <s:fielderror></s:fielderror> 17 </body> 18 </html>
3:代码方式验证Action中指定的方法(写验证方法命名规则,validate+要验证的方法名称,举例如下所示:);
1 package com.bie.lesson10; 2 3 import com.opensymphony.xwork2.ActionSupport; 4 5 /** 6 * @author Author:别先生 7 * @date Date:2017年9月24日 下午3:28:25 8 * 9 * 1:注意,如果想要用struts的数据校验功能,必须继承ActionSupport或者实现相关接口; 10 */ 11 public class CheckAction extends ActionSupport{ 12 13 /** 14 * 15 */ 16 private static final long serialVersionUID = 1L; 17 18 //封装请求数据 19 private User user; 20 public void setUser(User user) { 21 this.user = user; 22 } 23 public User getUser() { 24 return user; 25 } 26 27 //重写数据校验的功能 28 /*@Override 29 public void validate() { 30 //用户名非空校验 31 if(user.getName() == null || "".equals(user.getName())){ 32 //保存错误信息 33 super.addFieldError("name", "用户的账号不能为空。"); 34 } 35 //密码非空校验 36 if(user.getPassword() == null || "".equals(user.getPassword())){ 37 //保存错误信息 38 super.addFieldError("password", "用户的密码不能为空"); 39 } 40 //用户的邮箱校验 41 if(user.getEmail() == null || "".equals(user.getEmail())){ 42 //保存错误信息 43 super.addFieldError("email", "用户的邮箱不能为空"); 44 } 45 //用户的生日不能为空 46 if(user.getBirthday() == null || "".equals(user.getBirthday())){ 47 //保存错误信息 48 super.addFieldError("birthday" , "用户的生日不能为空"); 49 } 50 51 }*/ 52 53 54 public void validatecheckData() { 55 //用户名非空校验 56 if(user.getName() == null || "".equals(user.getName())){ 57 //保存错误信息 58 super.addFieldError("name", "用户的账号不能为空。"); 59 } 60 //密码非空校验 61 if(user.getPassword() == null || "".equals(user.getPassword())){ 62 //保存错误信息 63 super.addFieldError("password", "用户的密码不能为空"); 64 } 65 //用户的邮箱校验 66 /*if(user.getEmail() == null || "".equals(user.getEmail())){ 67 //保存错误信息 68 super.addFieldError("email", "用户的邮箱不能为空"); 69 }*/ 70 //用户的生日不能为空 71 /*if(user.getBirthday() == null || "".equals(user.getBirthday())){ 72 //保存错误信息 73 super.addFieldError("birthday" , "用户的生日不能为空"); 74 }*/ 75 76 } 77 78 //业务方法 79 public String checkData(){ 80 81 System.out.println(user); 82 return SUCCESS; 83 } 84 85 //用户列表的展示 86 public String list(){ 87 88 System.out.println("模拟是否验证"); 89 return "list"; 90 } 91 92 }
4:xml方式验证Action中所有的方法(代码验证比较繁琐,设计很多重复的验证逻辑,例如,非空验证,数值验证,email,日期等等,struts2对于常用的验证,进行了封装,即提供了验证器,验证指定额常用业务逻辑;);
4.1:Struts提供的验证器:xwork-core-2.3.16.3.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 -->
4.2:如何写xml,从而定义验证规则:
(a)xml文件名称语法:ActionClassName-validation.xml,注意,此xml需要与当前要验证的action在同一个目录;
(b)举例:CheckXmlAction-validation.xml,找到xwork-core-2.3.16.3.jar/xwork-validator-1.0.3.dtd复制一下dtd的头文件:
<?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">
1 package com.bie.lesson11; 2 3 import com.opensymphony.xwork2.ActionSupport; 4 5 /** 6 * @author Author:别先生 7 * @date Date:2017年9月24日 下午3:28:25 8 * 9 * 1:注意,如果想要用struts的数据校验功能,必须继承ActionSupport或者实现相关接口; 10 */ 11 public class CheckXmlAction extends ActionSupport{ 12 13 /** 14 * 15 */ 16 private static final long serialVersionUID = 1L; 17 18 //封装请求数据 19 private User user; 20 public void setUser(User user) { 21 this.user = user; 22 } 23 public User getUser() { 24 return user; 25 } 26 27 28 //业务方法 29 public String checkData(){ 30 31 System.out.println(user); 32 return SUCCESS; 33 } 34 35 /*//用户列表的展示 36 public String list(){ 37 38 System.out.println("模拟是否验证"); 39 return "list"; 40 }*/ 41 42 }
验证的xml配置,注意起名规则:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE validators PUBLIC 3 "-//Apache Struts//XWork Validator 1.0.3//EN" 4 "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"> 5 <validators> 6 7 <!-- 验证的每一字段用field表示 --> 8 <field name="user.name"> 9 <!-- 指定使用的验证器 --> 10 <field-validator type="requiredstring"> 11 <!-- 验证失败的错误提示信息 --> 12 <message>用户名不能为空</message> 13 </field-validator> 14 </field> 15 16 <!-- 验证的每一字段用field表示 --> 17 <field name="user.password"> 18 <!-- 指定使用的验证器 --> 19 <field-validator type="requiredstring"> 20 <!-- 验证失败的错误提示信息 --> 21 <message>密码不能为空</message> 22 </field-validator> 23 24 <!-- 密码的长度校验 --> 25 <field-validator type="stringlength"> 26 <param name="minLength">6</param> 27 <param name="maxLength">10</param> 28 <message>密码长度必须6-10位</message> 29 </field-validator> 30 </field> 31 32 <!-- 验证日期和验证邮箱 --> 33 <field name="user.email"> 34 <field-validator type="email"> 35 <message>邮箱格式不正确</message> 36 </field-validator> 37 </field> 38 <field name="user.birthday"> 39 <field-validator type="date"> 40 <message>日期格式不正确</message> 41 </field-validator> 42 </field> 43 44 </validators> 45 46
5:xml方式验证Action中指定的方法(与上面xml验证方式大致相同,验证xml文件内容不变);
5.1:命名规则:语法,ActionClassName-ActionName-validation.xml,举例:CheckXmlAction-data_checkData-validation.xml即验证CheckXmlAction的checkData方法;
验证总结
代码验证:
重写validate() , 验证action所有方法
Validate方法名(), 验证指定“方法名”的方法
Xml:
验证所有方法: ActionClassName-validation.xml
验证指定方法: ActionClassName-actionName-validation.xml
代码验证:
比较灵活,可以满足所有的需求.
比较繁琐,要写重复的验证判断逻辑!
适合: 表单字段较少的情况用!
XML验证:
通用,但不够灵活; 可以验证特定简单的业务。
适合: 验证表单字段较多,可以大大简化代码!
(配置文件过多)
6:验证错误处理的三种方法,如果数据输入错误就依旧跳转到输入数据的界面,这点在struts.xml里面控制:
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 4 "http://struts.apache.org/dtds/struts-2.0.dtd"> 5 6 <struts> 7 <package name="checkXmlPackage" extends="struts-default"> 8 <!-- 注册失败跳转到注册页面,显示失败信息 --> 9 <global-results> 10 <result name="input">/dataXmlCheck.jsp</result> 11 </global-results> 12 13 <action name="data_*" class="com.bie.lesson11.CheckXmlAction" method="{1}"> 14 <result name="success">/success2.jsp</result> 15 <!-- <result name="input">/error.jsp</result> --> 16 <!-- <result name="list">success2.jsp</result> --> 17 </action> 18 19 </package> 20 21 </struts> 22
然后在输入数据的页面进行错误提示:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ taglib prefix="s" uri="/struts-tags"%> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>数据校验</title> 9 10 <!-- 修改struts标签默认的样式: 不让换行 --> 11 <style type="text/css"> 12 ul{display: inline;} 13 ul li{display: inline;color: red;} 14 </style> 15 16 </head> 17 <body> 18 19 <!-- 显示的是Struts2在运行时期产生的所有错误 --> 20 <!-- 方式一 --> 21 <%-- <s:fielderror></s:fielderror> --%> 22 23 <%-- <s:fielderror fieldName="user.name"></s:fielderror> 24 <s:fielderror fieldName="user.password"></s:fielderror> 25 <s:fielderror fieldName="user.email"></s:fielderror> 26 <s:fielderror fieldName="user.birthday"></s:fielderror> --%> 27 28 <form action="${pageContext.request.contextPath}/data_checkXmlData.action" method="post"> 29 账号:<input type="text" name="user.name"/> 30 <!-- 方式二 --> 31 <s:fielderror fieldName="user.name"></s:fielderror><br/> 32 密码:<input type="password" name="user.password"/> 33 <s:fielderror fieldName="user.password"></s:fielderror><br/> 34 邮箱:<input type="text" name="user.email"/><br/> 35 <%-- <s:fielderror fieldName="user.email"></s:fielderror> --%> 36 生日:<input type="text" name="user.birthday"/><br/> 37 <%-- <s:fielderror fieldName="user.birthday"></s:fielderror> --%> 38 <input type="submit" value="注册"/> 39 <input type="reset" value="重置"/> 40 </form> 41 42 </body> 43 </html>
方式三(fielderror.ftl文件):
方式3: 修改标签定义的模板
找到fielderror标签定义的模板文件:
Struts-core.jar\template\simple\ fielderror.ftl
把修改后的fielderror.ftl文件,放到src/ template/ simple/ 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/>
以上是关于一脸懵逼学习Struts数据校验,数据回显,模型驱动,防止表单重复提交。的主要内容,如果未能解决你的问题,请参考以下文章
一脸懵逼学习oracle(图形化界面操作---》PLSQL图形化界面)