java代码如下:

package com.struts1.form;

import org.apache.struts.validator.ValidatorForm;

public class LoginValidatorForm extends ValidatorForm {
	private static final long serialVersionUID = 1L;

	private String email = null;

	private String password = null;

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}



package com.struts1.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.struts1.form.LoginValidatorForm;

public class LoginValidatorAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		LoginValidatorForm loginValidatorForm = (LoginValidatorForm) form;
		if (!"admin@163.com".equals(loginValidatorForm.getEmail()) || !"admin123".equals(loginValidatorForm.getPassword())) {
			return mapping.findForward("fail");
		}
		return mapping.findForward("success");
	}

}




web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>struts1</display-name>
	<servlet>
		<servlet-name>action</servlet-name>
		<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
		<init-param>
			<param-name>config</param-name>
			<param-value>/WEB-INF/struts-config.xml</param-value>
		</init-param>
		<load-on-startup>2</load-on-startup>
	</servlet>


	<!-- Standard Action Servlet Mapping -->
	<servlet-mapping>
		<servlet-name>action</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>


	<welcome-file-list>
		<welcome-file>validateLogin.jsp</welcome-file>
	</welcome-file-list>
</web-app>



struts-config.xml:

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
		<form-bean name="loginValidatorForm" type="com.struts1.form.LoginValidatorForm">
			<form-property name="email" type="java.lang.String" />
			<form-property name="password" type="java.lang.String" />
		</form-bean>
	</form-beans>

	<global-exceptions>
	</global-exceptions>

	<global-forwards>
	</global-forwards>

	<action-mappings>
		<action path="/validateLogin" type="com.struts1.action.LoginValidatorAction"
			name="loginValidatorForm" scope="request" validate="true"
			input="/validateLogin.jsp">
			<forward name="fail" path="/fail.jsp" />
			<forward name="success" path="/success.jsp" />
		</action>
	</action-mappings>

	<message-resources parameter="MessageResources" />

	<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
		<set-property property="pathnames"
			value="/org/apache/struts/validator/validator-rules.xml,  
               /WEB-INF/validation.xml" />
	</plug-in>
	
</struts-config>




validation.xml:


<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE form-validation PUBLIC
     "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN"
     "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">

<form-validation>

	<formset>

		<form name="loginValidatorForm">
			<field property="email" depends="required,email">
				<arg key="loginValidatorForm.email" />
			</field>
			<field property="password" depends="required,mask">
				<arg key="loginValidatorForm.password" />
				<var>
					<var-name>mask</var-name>
					<var-value>^[0-9a-zA-Z]*$</var-value>
				</var>
			</field>
		</form>

	</formset>

</form-validation>



MessageResources.properties:


#   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.

# -- Standard Errors --
errors.header=<ul>
errors.prefix=<li class="error">
errors.suffix=</li>
errors.footer=</ul>

# -- Struts Validator Error Messages --
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.

# -- other --
errors.cancel=Operation cancelled.
errors.detail={0}
errors.general=The process did not complete. Details should follow.
errors.token=Request could not be completed. Operation is not in sequence.
errors.twofields=The '{0}' field must have the same value as the '{1}' field.
errors.name.required=Name is required.
errors.secret.required=Please tell me a secret (it doesn't have to be true).

# -- formatting --
format.date=M/d/yyyy h:mm a z
format.currency=$#,##0.00;$(#,##0.00)

# -- buttons --
button.submit=Submit
button.cancel=Cancel
button.confirm=Confirm
button.reset=Reset
button.save=Save

# -- messages --
message.detail={0}
message.example.simple=This is a simple message.
message.example.replaceable=This is <strong>{0}</strong> message with <strong>{1}</strong> parameters.
message.welcome=Welcome to the examples page.

# -- prompts --
prompt.name=Name
prompt.secret=Secret phrase

prompt.byte=Byte
prompt.creditCard=Credit Card
prompt.date=Date
prompt.double=Double
prompt.email=Email
prompt.float=Float
prompt.integer=Integer
prompt.long=Long
prompt.mask=Mask
prompt.min=Min. Length
prompt.max=Max. Length
prompt.range=Range
prompt.required=Required
prompt.short=Short
prompt.password=Password
prompt.password2=Password confirmation

loginValidatorForm.email=email
loginValidatorForm.password=password



validateLogin.jsp:

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-nested" prefix="nested" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
	<html:form action="validateLogin" method="post" οnsubmit="return validateLoginValidatorForm(this);">  
        email:<html:text property="email" />  
        password:<html:password property="password" />  
        <html:submit value="login" />  
    </html:form>  
<html:javascript formName="loginValidatorForm"/>
</body>
</html>




测试:

struts1验证_struts

struts1验证_xml_02


一、Struts的插件机制:
  Struts通过插件机制来给用户扩展Struts功能。
  1.提供一个PlugIn接口,init(),destroy()。自定义的插件类就去实现就个类。
  2.在Struts的配置文件中,用<plug-in className="...">标记来注册到Struts框架中。


二、Struts中验证框架的使用:
 1.安装:
  1) 在struts配置文件中添加<plug-in>标记来加载验证框架插件:

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
    <set-property property="pathnames"
        value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
  </plug-in>


  2) 把validator-rules.xml和validation.xml放置在项目的WEB-INF目录下。
  3) 在struts配置文件中添加一个<message-resources parameter="MessageResources" />,然后在项目源代码路径中添加MessageREsources_xx_xx.properties,在资源文件中把validator-rules.xml中的一些验证框架要使用到消息拷贝进去。


 2.使用:
   1) 验证框架要求ActionForm必须继承自ValidatorForm或它的子类ValidatorActionForm,不能重写validate()方法,而且在struts配置文件要配置成需要验证(把对应<action>标记的validate设置为true)。
   2) 修改validation.xml来配置针对某个ActionForm的验证规则。
   3) 在验证失败后跳转到的页面中用<html:messages>来显示错误消息。


 3.用Validator框架做客户端javaScript的验证:
   1) 在jsp页面中包含<html:javascript>标签,用formName属性指定要验证的表单名。
      表单名要跟validation.xml中配置的name一致。
        如:<html:javascript formName="userForm"/>
   2) 对需要验证的表单定义onsubmit事件,其中事件名称为validate+"要验证的表单名"
        如:

<form name="userForm" action="login.do" 
                     οnsubmit="return validateUserForm(this)">


三、ValidateForm和ValidateActionForm的区别
 如果表单Bean继承自ValidateForm:那么在validation.xml文件中<form>标记配置的name属性值应该对应成struts配置文件中<action>标记的name属性值。


如果表单Bean继承自ValidateActionForm:那么在validation.xml文件中<form>标记配置的name属性值应该对应成struts配置文件中<action>标记的path属性值。这种方式就可针对同一个表单在不同请求路径下的不同验证。


扩展四、如果使用了DispatchAction时,Validate验证框架无法完成工作了。解决方法就是重写org.apache.struts.validator.FieldChecks中所有的方法,添加对parameter="xxx"的区别。