当前页面: 开发资料首页 → Java 专题 → 在struts中用validator作服务器端验证
在struts中用validator作服务器端验证
摘要: 在struts中用validator作服务器端验证
</td>
</tr>
<tr>
<td height="35" valign="top" class="ArticleTeitle">
这个例子用的是struts1.2.4自带的,但愿能给你学习带来帮助。例子的目录结构和所有用到的文件,请从本站下载。
一、Form bean与jsp页面
先看jsp页面的表单,内容有姓名,地址,省(市),县,邮编,电话,E-mail。
下面是Form bean,它在struts-config.xml中的命名是registrationForm。一定要继承ValidatorForm,注意这个CityStateZip属性,它用来存放:省(市),县,邮编三项内容。
package org.apache.struts.webapp.validator;
<table width="725" border="0">
<tr>
<td width="449">
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.ValidatorForm;
public final class RegistrationForm extends ValidatorForm implements Serializable {
private String action = null;
private String sFirstName = null;
private String sLastName = null;
private String sAddr = null;
private CityStateZip csz = new CityStateZip();
private String sPhone = null;
private String sEmail = null;
public String getAction() {
return action;
}
</td>
<td width="266" valign="top">
</td>
</tr>
</table>
public void setAction(String action) {
this.action = action;
}
public String getFirstName() {
return sFirstName;
}
public void setFirstName(String sFirstName) {
this.sFirstName = sFirstName;
}
public String getLastName() {
return sLastName;
}
public void setLastName(String sLastName) {
this.sLastName = sLastName;
}
public String getAddr() {
return sAddr;
}
public void setAddr(String sAddr) {
this.sAddr = sAddr;
}
public CityStateZip getCityStateZip() {
return csz;
}
public void setCityStateZip(CityStateZip csz) {
this.csz = csz;
}
public String getPhone() {
return sPhone;
}
public void setPhone(String sPhone) {
this.sPhone = sPhone;
}
public String getEmail() {
return sEmail;
}
public void setEmail(String sEmail) {
this.sEmail = sEmail;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
action = null;
sFirstName = null;
sLastName = null;
sAddr = null;
csz = new CityStateZip();
sPhone = null;
sEmail = null;
}
}
这是类CityStateZip的源码,它对应省(市),县,邮编,看后面的jsp页面就知道:邮编存放在字符串数组sZipPostal[]的第二项,其它两项为null。
package org.apache.struts.webapp.validator;
public class CityStateZip implements java.io.Serializable {
private String sCity = null;
private String sStateProv = null;
private String[] sZipPostal = new String[3];
public String getCity() {
return sCity;
}
public void setCity(String sCity) {
this.sCity = sCity;
}
public String getStateProv() {
return sStateProv;
}
public void setStateProv(String sStateProv) {
this.sStateProv = sStateProv;
}
public String getZipPostal(int index) {
return sZipPostal[index];
}
public void setZipPostal(int index, String value) {
this.sZipPostal[index] = value;
}
}
这是含表单的registration.jsp,
<%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/tags/struts-logic" prefix="logic" %>
<head>
</head>
<body bgcolor="white">
<table border="0" width="100%">
<tr>
<th align="left">
</th>
<td align="left">
</td>
</tr>
<tr>
<th align="left">
</th>
<td align="left">
</td>
</tr>
<tr>
<th align="left">
</th>
<td align="left">
</td>
</tr>
<tr>
<th align="left">
</th>
<td align="left">
</td>
</tr>
<tr>
<th align="left">
</th>
<td align="left">
</td>
</tr>
<tr>
<th align="left">
</th>
<td align="left">
</td>
</tr>
<tr>
<th align="left">
</th>
<td align="left">
</td>
</tr>
<tr>
<th align="left">
</th>
<td align="left">
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</body>
要注意的是下面三个属性的写法,它们的值将会存入form bean(即registrationForm)的CityStateZip属性:
二、struts-config.xml配置
<?xml version="1.0" encoding="iso-8859-1"?>
struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://struts.apache.org/dtds/struts-config_1_2.dtd">
<form-beans>
<form-bean name="registrationForm" type="org.apache.struts.webapp.validator.RegistrationForm"/>
</form-beans>
type="org.apache.struts.webapp.validator.RegistrationAction"
name="registrationForm"
scope="request"
validate="true"
input="/validator/registration.jsp">
property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
1、struts-config.xml中利用插件加入验证组件validator。涉及四个重要文件,一个是处理表单的RegistrationAction.java,这里仅在日志中输出信息,没有数据库存储,无错误时转到"success"页面。
package org.apache.struts.webapp.validator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public final class RegistrationAction extends Action {
/**
* Commons Logging 日志.
*/
private Log log = LogFactory.getFactory().getInstance(this.getClass().getName());
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
RegistrationForm info = (RegistrationForm)form;
CityStateZip city=info.getCityStateZip();
String action = request.getParameter("action");
if(log.isInfoEnabled()){
log.info("1:="+city.getCity());
log.info("2:="+city.getStateProv());
log.info("3:="+city.getZipPostal(1));
}
// Was this transaction cancelled?
if (isCancelled(request)) {
if (log.isInfoEnabled()) {
log.info(
" "
+ mapping.getAttribute()
+ " - Registration transaction was cancelled");
}
removeFormBean(mapping, request);
return (mapping.findForward("success"));
}
return mapping.findForward("success");
}
protected void removeFormBean(
ActionMapping mapping,
HttpServletRequest request) {
// Remove the obsolete form bean
if (mapping.getAttribute() != null) {
if ("request".equals(mapping.getScope())) {
request.removeAttribute(mapping.getAttribute());
} else {
HttpSession session = request.getSession();
session.removeAttribute(mapping.getAttribute());
}
}
}
}
2、另一个是资源属性文件:ApplicationResources1_zh_CN.properties,使用时请用JDK自带的native2ascii.exe转换为ApplicationResources_zh_CN.properties,并与class文件放在一起。
d:\java\>native2ascii -encoding GBK d:\java\ApplicationResources1_zh_CN.properties >d:\java\ApplicationResources_zh_CN.properties
其中必须包括# Errors中的内容(因为在validator-rules.xml中用到这些信息)
ApplicationResources1_zh_CN.properties
button.cancel=取消
button.confirm=配置
button.reset=重设
button.save=提交
# Errors
errors.footer=
errors.header=
验证错误
你必须更正下列错误:
errors.ioException=I/O exception rendering error messages: {0}
error.database.missing=
User database is missing, cannot validate logon credentials
errors.required={0} 是必填项.
errors.minlength={0} 不能少于 {1} 个字符.
errors.maxlength={0} 不能大于 {1} 个字符.
errors.invalid={0} 是无效的.
errors.byte={0} must be an byte.
errors.short={0} must be an short.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.float={0} must be an float.
errors.double={0} must be an double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid e-mail address.
# Registration Form
registrationForm.title=服务器端验证
registrationForm.title.create=创建用户
registrationForm.title.edit=编辑用户信息
registrationForm.firstname.displayname=你的名字:
registrationForm.lastname.displayname=你的姓:
registrationForm.addr.displayname=你的住址:
registrationForm.city.displayname=省市:
registrationForm.stateprov.displayname=州县:
registrationForm.zippostal.displayname=邮编:
registrationForm.phone.displayname=电话:
registrationForm.email.displayname=E-mail:
registrationForm.lastname.maskmsg=姓只能是字符,不能有空格.
3、另两个文件就是下面提到的。
三、Validator配置
复制Validator-rules.xml,Validation.xml到当前应用程序的路径下,比如WEB-INF/(可从struts-examples.war解压后得到)。
1、 Validator-rules.xml里定义的是验证器,以
的方式存储,默认情况下包含的规则已经可以满足我们程序的需要,一般无需修改。
2、配置validation.xml文件,里面定义的是应用程序特有的验证规则内容,针对表单的属性用正则表达式给出具体的验证法则。
<?xml version="1.0" encoding="iso-8859-1"?>
form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
phone
^\(?(\d{3})\)?[-| ]?(\d{3})[-| ]?(\d{4})$
zip
^\d{5}\d*$
<formset>
zip
^\d{5}(-\d{4})?$
<form name="registrationForm">
mask
^\w+$
minlength
5
mask
^[a-zA-Z]*$
maxlength
10
mask
^[a-zA-Z]*$
mask
^[a-zA-Z]*$
mask
mask
</form>
</formset>
</form-validation>
四、测试:下载站长的目录结构TestStruts,将其放入Tomcat的webapps下,在浏览器中输入:
http://127.0.0.1:8080/TestStruts/validator/registration.jsp
function TempSave(ElementID)
{
CommentsPersistDiv.setAttribute("CommentContent",document.getElementById(ElementID).value);
CommentsPersistDiv.save("CommentXMLStore");
}
function Restore(ElementID)
{
CommentsPersistDiv.load("CommentXMLStore");
document.getElementById(ElementID).value=CommentsPersistDiv.getAttribute("CommentContent");
}
</td>
</tr>
<tr>
↑返回目录
前一篇: struts中的文件上传
后一篇: Struts中不同的Action和ActionForm组合