struts1.x的动态验证实例

1.写一个Action类:
public class LoginAction extends Action {
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		DynaValidatorForm loginForm = (DynaValidatorForm) form;		
		return mapping.findForward("success");
	}
	
}


2.配置struts.xml文件:
<?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="loginForm" type="org.apache.struts.validator.DynaValidatorForm">
      <form-property name="userName" type="java.lang.String" />
  </form-bean>
  </form-beans>
  <global-exceptions />
  <global-forwards />
   <action-mappings >
    <action  attribute="loginForm" input="/login.jsp"
      name="loginForm" path="/login"  scope="request"
      type="com.and4walker.struts.action.LoginAction" >
      <forward name="success" path="/success.jsp" />
     </action>
  </action-mappings>
  <message-resources parameter="com.and4walker.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>


3.建立一个validation.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE form-validation PUBLIC "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN" "validator_1_1_3.dtd" >
<form-validation>
	<formset>
		<form name="loginForm">
			<field property="userName" depends="required,minlength">
				<arg key="label.username" resource="true" />
				<arg1 key="${var:minlength}" resource="false" />
				<var>
					<var-name>minlength</var-name>
					<var-value>5</var-value>
				</var>
			</field>
		</form>
	</formset>
</form-validation>


4.配置ApplicationResources.properties文件:
# Resources for parameter 'com.and4walker.struts.ApplicationResources'
# Project strutsupload
label.username=username
<!-- 下面的对应关系可以在validator-rules.xml中找到 -->
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.


5.建立login.jsp跟success.jsp:
login.jsp:
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<html> 
	<body>
	    <html:javascript formName="loginForm"/>
		<html:form action="/login"  onsubmit="return validateLoginForm(this)"> 
			姓名: <html:text property="userName"/><br/>
			<html:submit/>
		</html:form>
	</body>
</html>

success.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
测试成功!

你可能感兴趣的:(apache,html,jsp,xml,struts)