rumengqiang 2012-11-23
目标: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服务器端验证的知识。