JavaWeb -- Struts1 动态bean, 动态校验, 动态生成javascript 表单校验

1. 动态formbean.

表单 JSP:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP '1.jsp' starting page</title>
  </head>
  
  <body>
    
    <html:errors/>   <!--错误回显-->
    <html:javascript formName="UserFormBean"/>  <!--动态生成javascript前端校验, onsubmit方法格式为 validate + formName (this)-->
    <html:form action="/register" οnsubmit="return validateUserFormBean(this)">
    	用户名:<input type="text" name="username"><br/>
    	密码:<input type="password" name="password"><br/>
    	确认密码:<input type="password" name="password2"><br/>
    	电子邮箱:<input type="text" name="email"><br/>
    	生日:<input type="text" name="birthday"><br/>
    	<input type="submit" value="注册">
    </html:form>
    
  </body>
</html>

struts-config.xml,配置动态formbean 和 校验需要的配置文件

<?xml version="1.0" encoding="UTF-8" ?>

<!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>

	<!--动态bean-->
	<form-beans>
		<form-bean name="UserFormBean" type="org.apache.struts.validator.DynaValidatorForm">
			<form-property name="username" type="java.lang.String"></form-property>
			<form-property name="password" type="java.lang.String"></form-property>
			<form-property name="password2" type="java.lang.String"></form-property>
			<form-property name="email" type="java.lang.String"></form-property>
			<form-property name="birthday" type="java.lang.String"></form-property>
		</form-bean>
	</form-beans>


	<action-mappings>
	
		<action path="/register" 
				name="UserFormBean" 
				type="cn.itcast.web.action.RegiserAction"
				input="/1.jsp">
				
		</action>
	</action-mappings>
	
	
	<message-resources parameter="MessageResource"></message-resources>
	
	<!--校验配置-->
	<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="UTF-8" ?>

<!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>

<global>
		<!-- Custom Validator 自定义 校验器 -->
		<validator name="twofields" 
                   classname="examples.validator.CustomValidator" 
                   method="validateTwoFields" 
                   methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionMessages,
                       javax.servlet.http.HttpServletRequest" 
                   msg="errors.twofields" />
	</global>

	

	<formset>
		<!-- Form for Validation example -->
		<form name="UserFormBean">

			<field property="username" depends="required,minlength,maxlength,mask">
				<arg key="用户名" resource="false" position="0" />
				
				<arg name="minlength" key="${var:minlength}" position="1" resource="false"/>
				<arg name="maxlength" key="${var:maxlength}" position="1" resource="false"/>
				<var>
					<var-name>minlength</var-name>
					<var-value>3</var-value>
				</var>
				<var>
					<var-name>maxlength</var-name>
					<var-value>6</var-value>
				</var>
				
				<var>
					<var-name>mask</var-name>
					<var-value>[A-Z]{3,6}</var-value>
				</var>
				
			</field>
			
			
			<field property="email" depends="email">
				<arg key="邮箱" resource="false" position="0"/>
			</field>
			
			<field property="birthday" depends="date">
				<arg key="prompt.birthday"  position="0"/>
			</field>
			
			<field property="password" depends="required,minlength,twofields">
				<arg key="密码" position="0" resource="false"/>
				<arg name="minlength" key="${var:minlength}" resource="false"  position="1"/>
				<arg name="twofields" key="确认密码"  position="1" resource="false"/>
				<var>
					<var-name>minlength</var-name>
					<var-value>5</var-value>
				</var>
				<var>
					<var-name>secondProperty</var-name>
					<var-value>password2</var-value>
				</var>
			</field>
			

		</form>
	</formset>
</form-validation>

自定义校验器: CustomValidator.java

/**
 * A custom validator example
 *
 * @version $Rev: 471754 $ $Date: 2006-11-06 08:55:09 -0600 (Mon, 06 Nov 2006) $
 */
public class CustomValidator {

    // ------------------------------------------------------------ Constructors

    /**
     * Constructor for CustomValidator.
     */
    public CustomValidator() {
        super();
    }

    // ---------------------------------------------------------- Public Methods

    /**
     * Example validator for comparing the equality of two fields
     *
     * http://struts.apache.org/userGuide/dev_validator.html
     * http://www.raibledesigns.com/page/rd/20030226
     */
    public static boolean validateTwoFields(
        Object bean,
        ValidatorAction va,
        Field field,
        ActionMessages errors,
        HttpServletRequest request) {

        String value =
            ValidatorUtils.getValueAsString(bean, field.getProperty());
        String property2 = field.getVarValue("secondProperty");
        String value2 = ValidatorUtils.getValueAsString(bean, property2);

        if (!GenericValidator.isBlankOrNull(value)) {
            try {
                if (!value.equals(value2)) {
                    errors.add(
                        field.getKey(),
                        Resources.getActionMessage(request, va, field));

                    return false;
                }
            } catch (Exception e) {
                errors.add(
                    field.getKey(),
                    Resources.getActionMessage(request, va, field));
                return false;
            }
        }
        return true;
    }
}

获得formbean的action

public class RegiserAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
	
		DynaActionForm daf = (DynaActionForm) form;  //username  password
		
		String username = daf.getString("username");
		String password = daf.getString("password");
		String email = daf.getString("email");
		System.out.println(username);
		
		
		User user = new User();
		BeanUtils.copyProperties(user, daf);  //可以的
		
		return super.execute(mapping, form, request, response);
	}

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  
  <servlet>
  	<servlet-name>ActionServlet</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>
  
  <servlet-mapping>
  	<servlet-name>ActionServlet</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>





 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值