`

快乐编程-知识分享-Struts1.x学习-validator-003

阅读更多

目标:struts1.x的四种服务器端验证

对象:适合自学者、初学者、兴趣爱好者。

理念:先行动(Coding),后理解(Thinking)在最短的时间内采取最大量的Coding分享越多,收获越大

--------------------------------------------------------------------------------------------------------------------------------

一、第一种验证,在自定义ActionForm类中重写validate方法,核心代码如下:

 

package com.raky.train.validate1;

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;

/**
 * validator by LoginForm
 * 1.> override ActionForm validate method
 * 2.> strutsConfig.xml action config validate="true"
 * 3.> strutsConfig.xml action config input="*.jsp"
 * 4.> jsp page add <html:errors/>
 * 
 * jsp request --> LoginForm validate method --> LoginAction
 * 
 * @author raky
 * @version v1.0
 * 
 */
public class LoginForm extends ActionForm {
	
	private static final long serialVersionUID = 8490608276362181884L;
	
	private String username;
	
	private String password;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	/** 
	 * Method validate
	 * @param mapping
	 * @param request
	 * @return ActionErrors
	 */
	@Override
	public ActionErrors validate(ActionMapping mapping,	HttpServletRequest request) {
		ActionErrors errors = new ActionErrors();
		if(null == this.username || this.username.equals("")){
			errors.add("username",new ActionMessage("validate.err.username.required","username"));
		}
		if(null == this.password || this.password.equals("")){
			errors.add("password",new ActionMessage("validate.err.password.required","password"));
		}	
		return errors;
	}

	/** 
	 * Method reset
	 * @param mapping
	 * @param request
	 */
	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		this.username = null;
		this.password = null;
	}
}

 

 二、第二种验证,在自定义Action类中execute方法中添加验证代码,核心代码如下:

 

package com.raky.train.validate2;

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 org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
/**
 * validator by LoginAction
 * 1.> strutsConfig.xml action config input="*.jsp"
 * 2.> override execute method add validate program
 * 3.> jsp page add <html:errors/>
 * 
 * @author raky
 * @version v1.0
 * 
 */
public class LoginAction extends Action  {
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		ActionForward forward = null;
		LoginForm loginForm = (LoginForm)form;
		//validate program
		ActionMessages errors = new ActionMessages();
		if(null == loginForm.getUsername() || loginForm.getUsername().equals("")){
			errors.add("username",new ActionMessage("validate.err.username.required","username"));
		}
		if(null == loginForm.getPassword() || loginForm.getPassword().equals("")){
			errors.add("password",new ActionMessage("validate.err.password.required","password"));			
		}		
		if(null != errors && errors.size() > 0){
			this.saveErrors(request, errors);
			return new ActionForward(mapping.getInput());
		}

		if(loginForm.getUsername().equals("admin") && loginForm.getPassword().equals("admin")){
			forward = mapping.findForward("success");
			request.setAttribute("loginForm", loginForm);
		}else{
			forward = mapping.findForward("failure");
		}		
		return forward;
	}	
}

 

 三、第三种验证,使用ValidatorPlugIn插件(struts1 Validator框架),核心代码如下:

 

package com.raky.train.validate3;

import org.apache.struts.validator.ValidatorForm;
/**
 * validator by ValidatorPlugIn
 * 1.> strutsConfig.xml config plug-in
 * 2.> strutsConfig.xml action config validate="true"
 * 3.> strutsConfig.xml action config input="*.jsp"
 * 4.> extends ValidatorForm
 * 5.> jsp page add <html:errors/>
 * 
 * @author raky
 * @version v1.0
 * 
 */
public class LoginForm extends ValidatorForm {

	private static final long serialVersionUID = -1162759977230749682L;
	
	private String username;
	private String password;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

 

核心strutsConfig.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>
	<!-- =================== Form Bean Definitions ==================== -->
	<form-beans>
		<form-bean name="loginForm1" type="com.raky.train.validate1.LoginForm" />
		<form-bean name="loginForm2" type="com.raky.train.validate2.LoginForm" />
		<form-bean name="loginForm3" type="com.raky.train.validate3.LoginForm" />
		<form-bean name="dynaForm4" type="org.apache.struts.validator.DynaValidatorForm">
			<form-property name="username" type="java.lang.String" />
			<form-property name="password" type="java.lang.String" />
		</form-bean>
	</form-beans>
	<!-- ================= Global Forward Definitions ================= -->
	<global-forwards>
		<forward name="success" path="/success.jsp" />
		<forward name="failure" path="/failure.jsp" />
	</global-forwards>
	<!-- =================== Action Definitions ==================== -->
	<action-mappings>
		<action path="/validater1/login" name="loginForm1"
			type="com.raky.train.validate1.LoginAction" input="/validater1/login.jsp"
			validate="true">
		</action>

		<action path="/validater2/login" name="loginForm2"
			type="com.raky.train.validate2.LoginAction" input="/validater2/login.jsp"
			validate="false">
		</action>

		<action path="/validater3/login" name="loginForm3"
			type="com.raky.train.validate3.LoginAction" input="/validater3/login.jsp"
			validate="true">
		</action>
		
		<action path="/validater4/login" name="dynaForm4"
			type="com.raky.train.validate4.LoginAction" input="/validater4/login.jsp"
			validate="true">
		</action>
	</action-mappings>

	<!-- ================ Message Resources Definitions ================ -->
	<message-resources parameter="MessageResources" />

	<!-- ================ Plug Ins Configuration ================ -->
	<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
		<set-property property="stopOnFirstError" value="true" />
		<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>
	<formset>
		<!-- Form for login Validation  -->
		<form name="loginForm3">
			<field property="username" depends="required">
			 	<msg name="required" key="validate.err.username.required" />
				<arg key="view.login.username" />
			</field>
			<field property="password" depends="required,minlength,maxlength">
			    <msg name="required"  key="validate.err.password.required" />
                <msg name="minlength" key="validate.err.password.minlength" />
                <msg name="maxlength" key="validate.err.password.maxlength" />
				<arg key="view.login.password" position="0"/>
				<arg name="minlength" key="${var:minlength}" resource="false"  position="1"/>
				<arg name="maxlength" key="${var:maxlength}" resource="false"  position="2"/>
				<var>
					<var-name>minlength</var-name>
					<var-value>5</var-value>
				</var>
				<var>
					<var-name>maxlength</var-name>
					<var-value>15</var-value>
				</var>
			</field>
		</form>
		<form name="dynaForm4" extends="loginForm3" />
	</formset>
</form-validation>

 

 四、第四种验证,使用Validator系列Form,(如DynaValidatorForm、LazyValidatorForm)+ ValidatorPlugIn插件(struts1 Validator框架)

 

/**
 * validator by ***ValidateForm + ValidatorPlugIn 
 * 1.> strutsConfig.xml config plug-in
 * 2.> strutsConfig.xml action config validate="true"
 * 3.> strutsConfig.xml action config input="*.jsp"
 * 4.> strutsConfig.xml form-bean config ***ValidateForm
 * 5.> jsp page add <html:errors/>
 * 
 * @author raky
 * @version v1.0
 * 
 */

 

 核心配置代码在第三种的strutsConfig.xml + validation.xml 中,在此省略。

 

以上验证,其中一个页面核心代码,如下:

 

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<c:set var="ctx" value="${pageContext.request['contextPath']}" />
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Raky train struts1.x - validate2 - Login page</title>
<html:base />
</head>
<body>
<h2>raky - struts1.x - validate2</h2>
<html:form action="/validater2/login" method="post">
<table>
	<tr>
		<td>用     户:</td>
		<td><html:text property="username"  maxlength="40" size="18" /><font color="red"><html:errors property="username" /></font></td>
	</tr>
	<tr>
		<td>密     码:</td>
		<td><html:password property="password"  maxlength="40" size="18" /><font color="red"><html:errors property="password" /></font></td>		
	</tr>
	<tr>
		<td align="center" colspan="2">
			<html:submit property="submitValue" value="确定" />
			<html:reset property="resetValue" value="重置" />
			<html:button property="btnValue" value="返回" onclick="location.href=${ctx}/" />
		</td>	
	</tr>
</table>
</html:form>
</body>
</html>

 总结:本文基本上总结了struts1.x服务器端验证的知识。

 

0
0
分享到:
评论

相关推荐

    hibernate-validator-5.0.0.CR2-dist.zip

    使用hibernate-validator 进行校验的jar包,里面包括了基础hibernate-validator-5.0.0.CR2.jar hibernate-validator-annotation-processor-5.0.0.CR2.jar 之外,还包括了el-api-2.2.jar javax.el-2.2.4等项目必不可...

    struts1.x使用common-validator验证框架

    Struts1.x是一个经典的Java Web开发框架,它极大地简化了MVC(模型-视图-控制器)模式的应用程序开发。而Common-Validator是Apache Commons项目的一部分,它为Struts1.x提供了一种强大的数据验证机制。这个框架允许...

    hibernate-validator-4.0.0.Beta1.jar

    hibernate-validator-4.0.0.Beta1.jar

    struts1.x和struts2.x区别

    Struts1.x的验证机制基于ActionForm,利用Commons Validator等库进行数据校验,而Struts2.x则采用了更为强大的验证框架,如XWork Validator,支持链式验证和更复杂的验证规则,使得数据验证更加全面和细致。...

    hibernate jar包:hibernate-commons-annotations-4.0.1.Final.jar等

    Hibernate.jar包,Hibernate可以应用在任何使用JDBC的场合,包含 hibernate-commons-annotations-4.0.1.Final.jar hibernate-core-4.1.12.Final.jar hibernate-ehcache-4.1.12....hibernate-validator-5.0.1.Final.jar

    struts1.x validator框架验证入门例子

    Struts1.x是一个经典的Java Web开发框架,它极大地简化了MVC(模型-视图-控制器)架构的应用程序开发。Validator框架是Struts1.x的一个重要组成部分,主要用于处理客户端和服务器端的数据验证。在这个入门例子中,...

    struts1.x apps 所有最新的Struts1.x项目应用

    Struts1.x是一款经典的Java Web框架,由Apache软件基金会开发并维护。它是MVC(Model-View-Controller)设计模式的实现,极大地简化了Java Web应用程序的开发过程。本资源集合包含了所有最新的Struts1.x项目应用,为...

    Python库 | bids-validator-1.8.5.dev0.tar.gz

    资源分类:Python库 所属语言:Python 资源全名:bids-validator-1.8.5.dev0.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    java Struts 1.x 框架 Web 开发

    9. **Validator框架**:Struts 1.x 的Validator框架用于数据验证,可以定义一系列规则来检查ActionForm中的属性值,确保数据的正确性。 10. **生命周期管理**:Struts 1.x 使用Servlet容器管理Bean的生命周期,对于...

    Python库 | schema-validator-halpa-0.0.3.post1.tar.gz

    资源分类:Python库 所属语言:Python 资源全名:schema-validator-halpa-0.0.3.post1.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    fluent-validator-1.0.6-API文档-中英对照版.zip

    赠送jar包:fluent-validator-1.0.6.jar; 赠送原API文档:fluent-validator-1.0.6-javadoc.jar; 赠送源代码:fluent-validator-1.0.6-sources.jar; 包含翻译后的API文档:fluent-validator-1.0.6-javadoc-API...

    spring-cloud-starter-gateway下hibernate-validator-5.0.3.Final.jar

    spring-cloud-starter-gateway下的依赖hibernate-validator-5.0.3.Final.jar

    hibernate-validator-5.2.4.Final.jar

    1. **约束注解**:Hibernate Validator 提供了一系列内置的约束注解,例如 @NotNull、@Size、@Email、@Pattern 等,可以直接在字段或方法上使用,以声明验证规则。这些注解可以单独使用,也可以组合使用,满足各种...

    hibernate-validator相关依赖jar包

    hibernate-validator相关依赖jar包,包括jboss-logging-3.1.0.CR2.jar,hibernate-validator-4.3.1.Final.jar,validation-api-1.0.0.GA.jar

    struts-2.3.30-all所有jar包

    commons-validator-1.3.1.jar, core-0.6.2.jar, dwr-1.1.1.jar, ezmorph-1.0.6.jar, freemarker-2.3.22.jar, google-collections-1.0.jar, google-gxp-0.2.4-beta.jar, guava-r09.jar, jackson-core-asl-1.9.2.jar, ...

    搭建struts1.x的jar包

    如果你正在寻找如何搭建Struts 1.x的开发环境,以下是一些关键的知识点,以及这些指定的jar包的作用。 首先,我们来看核心的`struts.jar`文件。这是Struts框架的核心库,包含了所有必要的类和接口,用于处理HTTP...

    hibernate-validator-6.0.12.Final-dist.zip

    Hibernate Validator用Annotations 给类或者类的属性加上约束,在运行期...该框架是十分容易的(就像参考文档中宣称的那样),几乎没有什么学习曲线,Validator 是一个验证框架 不需要和Hibernate的其他部分绑定就可以使用

    struts2.x jar

    Struts2.x是一个非常著名的Java Web开发框架,它基于Model-View-Controller(MVC)设计模式,旨在简化企业级应用程序的开发。Struts2.x的核心是它的Action类,它处理HTTP请求,并与业务逻辑进行交互,然后将结果传递...

    hibernate-validator-4.2.0.Final.jar

    hibernate-validator-4.2.0.Final.jar的下载

Global site tag (gtag.js) - Google Analytics