本文的字例子是在MyEclipse5.5下均運行成功
在struts1的標單驗證一般有兩種方式,一種是通過ActionForm的validate函數進行驗證,另一種就是利用validate框架進行驗證,下面將通過兩個非空驗證的簡單例子對這兩種驗證方法進行一下討論。
Validate函數驗證 public ActionErrors alidate(ActionMapping mapping, HttpServletRequest request)
這個驗證是 在客戶端的ActionForm的public ActionErrors alidate(ActionMapping mapping,HttpServletRequest request)方法中進行的,該函數通過對標單進行檢驗,返回一個ActionErrors的對象,如果這個對象爲空就返回到輸入頁面中,並通過<html:errors/>標籤進行錯誤的顯示,下面展示一下源代碼:
下面試是導航圖:
struts-config.xml:這裏主要是配置了一個Form和一個Action,注意validate="true"這是必須的。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<data-sources />
<form-beans >
<form-bean name="validateForm" type="com.qiudawei115.struts.form.ValidateForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
<action
attribute="validateForm"
input="/input.jsp"
name="validateForm"
path="/validate"
scope="request"
type="com.qiudawei115.struts.action.ValidateAction" validate="true">
<forward name="ok" path="/validateOk.jsp" />
</action>
</action-mappings>
<message-resources parameter="com.qiudawei115.struts.ApplicationResources" />
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
/WEB-INF/validation.xml"/>
</plug-in>
</struts-config>
輸入頁面input.jsp:通過<html:errors/>標籤來顯示錯誤
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<html>
<head>
<title>JSP for ValidateForm form</title>
<html:base/>
</head>
<body>
<html:form action="/validate" method="post" focus="testString" >
testString : <html:text property="testString"/><html:errors property="testString"/><br/>
<html:submit/><html:cancel/>
</html:form>
</body>
</html>
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
驗證通過頁面:validateOk.jsp
<!DOCTYPE HTML PUBLIC "-//W
<html:html lang="true">
<head>
<html:base />
<title>validateOk.jsp</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This a struts page. <br>
<bean:message key="ok"/>
</body>
</html:html>
ActionForm:com.qiudawei115.struts.form.ValidateForm.java:注意validate方法裏面內容
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.qiudawei115.struts.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
/**
* MyEclipse Struts
* Creation date:
*
* XDoclet definition:
* @struts.form name="validateForm"
*/
public class ValidateForm extends ActionForm {
/*
* Generated fields
*/
/** testString property */
private String testString;
/*
* Generated Methods
*/
/**
* Method validate
* @param mapping
* @param request
* @return ActionErrors
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
ActionErrors errors=new ActionErrors();
if(testString==null||testString.trim().length()<=0){
errors.add("testString", new ActionMessage("errors.required"));
}
return errors;
}
/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
}
/**
* Returns the testString.
* @return String
*/
public String getTestString() {
return testString;
}
/**
* Set the testString.
* @param testString The testString to set
*/
public void setTestString(String testString) {
this.testString = testString;
}
}
Action:com.qiudawei115.struts.action.ValidateAction.java這只是一個簡單導航
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.qiudawei115.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.qiudawei115.struts.form.ValidateForm;
/**
* MyEclipse Struts
* Creation date:
*
* XDoclet definition:
* @struts.action path="/validate" name="validateForm" input="/input.jsp" scope="request" validate="true"
*/
public class ValidateAction extends Action {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
ValidateForm validateForm = (ValidateForm) form;// TODO Auto-generated method stub
return mapping.findForward("ok");
}
}
com.qiudawei115.struts.ApplicationResources.properties資源文件
包含錯誤信息
# Resources for parameter 'com.qiudawei115.struts.ApplicationResources'
# Project Struts1Validate
# Basic Message
ok=Validate OK!
# Struts Validator Error Messages
errors.required=this is required.
Validate框架驗證
使用框架驗證需要在WEB-INF下添加兩個xml配置文件,validation.xml和validator-rules.xml,其中validator-rules.xml定義的是腳本,validation.xml由開發者自己添加驗證規則。所有的出錯信息從資源文件中讀取。
下面是導航圖:
Struts-config.xml:注意action標記的validate屬性,設置爲false表示在客戶端驗證,本例子是客戶端驗證。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<data-sources />
<form-beans >
<form-bean name="testForm" type="com.yourcompany.struts.form.TestForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
<action
attribute="testForm"
input="/input.jsp"
name="testForm"
path="/test"
scope="request"
type="com.yourcompany.struts.action.TestAction" validate="false">
<forward name="ok" path="/MyJsp.jsp" />
</action>
</action-mappings>
<message-resources parameter="com.yourcompany.struts.ApplicationResources" />
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
/WEB-INF/validation.xml"/>
</plug-in>
</struts-config>
Validation.xml:注意紅體字爲驗證的部分,arg0代表了資源文件中的{0}
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
<!--
This is a minimal Validator form file with a couple of examples.
-->
<global>
<!-- An example global constant
<constant>
<constant-name>postalCode</constant-name>
<constant-value>^/d{5}/d*$</constant-value>
</constant>
end example-->
</global>
<formset>
<form name="testForm">
<field property="testString" depends="required">
<!-- <msg name="required" key="errors.required"/> -->
<arg0 key="test"/>
</field>
</form>
</formset>
</form-validation>
資源文件com/yourcompany/struts/ApplicationResources.properties
# Resources for parameter 'com.yourcompany.struts.ApplicationResources'
test=testField
# Project StrutsValidate1
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is an invalid credit card number.
errors.email={0} is an invalid e-mail address.
入口input.jsp:注意:紅體部分表示客戶端生成的javascript代碼要求formName表示驗證的表單名字
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<html>
<head>
<title>JSP for TestForm form</title>
</head>
<body>
<html:javascript formName="testForm" staticJavascript="true" dynamicJavascript="true" />
<html:form action="/test" method="post" focus="testString" onsubmit="return validateTestForm(this);">
testString : <html:text property="testString"/><html:errors property="testString"/><br/>
<html:submit/><html:cancel/>
</html:form>
</body>
</html>
ActionForm: com.yourcompany.struts.form.TestForm.java注意這個Form一定要繼承自ValidaorForm,並且最好不要修改validate函數。
package com.yourcompany.struts.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.ValidatorForm;
/**
* MyEclipse Struts
* Creation date:
*
* XDoclet definition:
* @struts.form name="testForm"
*/
public class TestForm extends ValidatorForm {
/*
* Generated fields
*/
/** testString property */
private String testString;
/*
* Generated Methods
*/
/**
* Method validate
* @param mapping
* @param request
* @return ActionErrors
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
return null;
}
/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
}
/**
* Returns the testString.
* @return String
*/
public String getTestString() {
return testString;
}
/**
* Set the testString.
* @param testString The testString to set
*/
public void setTestString(String testString) {
this.testString = testString;
}
}
Action: com.yourcompany.struts.action.TestAction.java
package com.yourcompany.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.yourcompany.struts.form.TestForm;
/**
* MyEclipse Struts
* Creation date:
*
* XDoclet definition:
* @struts.action path="/test" name="testForm" input="/input.jsp" scope="request" validate="true"
*/
public class TestAction extends Action {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
TestForm testForm = (TestForm) form;// TODO Auto-generated method stub
return mapping.findForward("ok");
}
}
MyJsp.Jsp導航最終頁面
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE HTML PUBLIC "-//W
<html:html lang="true">
<head>
<html:base />
<title>MyJsp.jsp</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This a struts page. <br>
</body>
</html:html>
至此已經簡單的介紹了Struts1的兩種驗證方法,希望對大家有所幫助.如果有疑問,可向我索取源代碼,一起討論。