struts2+jquery+ajax表单验证

jopen 8年前

一、常见问题:

1.提示json-default包不存在或拦截器jsonValidationWorkflowStack不存在?

解决:struts2-json-plugin-xxx.jar

 

2.每验证一次,错误信息就累加一次,出现重复?

解决:如果你整合了spring,请将相应bean的singleton设为false(spring中的bean默认为单例模式,导致前次验证产生的错误信息一直存在)

 

二、Demo1:使用xhtml主题的表单验证

1.struts.xml

<?xml version="1.0" encoding="utf-8"?>  <!DOCTYPE struts PUBLIC      "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"      "http://struts.apache.org/dtds/struts-2.0.dtd">    <struts>      <package name="admin" extends="json-default" namespace="/admin">                    <action name="login" class="com.wogu.jwa.actions.IndexAction">              <result>/WEB-INF/views/login.jsp</result>          </action>            <action name="dologin" class="com.wogu.jwa.actions.LoginAction">              <result>/admin/index</result>              <result name="input">/WEB-INF/views/login.jsp</result>              <interceptor-ref name="jsonValidationWorkflowStack"/>          </action>      </package>  </struts>

2./WEB-INF/views/login.jsp

<%@ page pageEncoding="utf-8" contentType="text/html; charset=utf-8" %>  <%@ taglib prefix="s" uri="/struts-tags" %>  <!DOCTYPE html>  <html>  <head>      <title>struts2+jquery+Ajax表单验证 - WoguAdmin - power by wogu</title>      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">      <!--加入/struts即请求的静态资源-->      <script type="text/javascript" src="${pageContext.request.contextPath}/struts/jwa/js/jquery-1.7.1.min.js"></script>      <script type="text/javascript" src="${pageContext.request.contextPath}/struts/jwa/js/jquery.form.js"></script>      <script language="JavaScript" src="${pageContext.request.contextPath}/struts/utils.js" type="text/javascript"></script>      <script language="JavaScript" src="${pageContext.request.contextPath}/struts/xhtml/validation.js" type="text/javascript"></script>      <s:head theme="xhtml" />  </head>  <body>  <s:form id="myform" theme="xhtml" namespace="/admin" action="dologin" method="post">      <s:textfield name="username" label="用户名"/>      <s:textfield name="password" label="密 码"/>      <s:submit value=" 登录 "/>      <s:reset value=" 清除 "/>      <!--只验证,Action类不会被执行到-->      <s:hidden name="struts.validateOnly" value="true"/>      <!--必须加入-->      <s:hidden name="struts.enableJSONValidation" value="true"/>  </s:form>  </body>  </html>  <script type="text/javascript">  jQuery('#myform').ajaxForm({      'success' : function(errorsObject) {          StrutsUtils.clearValidationErrors(myform);          if(errorsObject.fieldErrors) {              StrutsUtils.showValidationErrors(myform, errorsObject);              return false;          }                    //validate success      }  });  </script>

3.com.wogu.jwa.actions.LoginAction

package com.wogu.jwa.actions;    import com.opensymphony.xwork2.ActionSupport;    public class LoginAction extends ActionSupport  {      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;      }  }

4.com/wogu/jwa/actions/LoginAction-validation.xml

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">    <validators>            <field name="username">          <field-validator type="requiredstring">              <message>You must enter a name</message>          </field-validator>      </field>            <field name="password">          <field-validator type="requiredstring">              <message>You must enter a password</message>          </field-validator>      </field>  </validators>

5.访问127.0.0.1:8080/admin/login

 

三、demo2:灵活的表单验证

1.创建自定义主题classpath/template/jwa

1-1.classpath/template/jwa/theme.properties

parent = simple

1-2.classpath/template/jwa/form-close.ftl

<#if parameters.validate == true>      <input type="hidden" name="struts.enableJSONValidation" value="true"/>  </#if>  <#if parameters.dynamicAttributes.validateOnly?default("false") == "true">      <input type="hidden" name="struts.validateOnly" value="true"/>  </#if>  <#include "/${parameters.templateDir}/simple/form-close.ftl" />  <#if parameters.validate == true>  <script type="text/javascript" src="${base}/struts/jwa/js/jquery.form.js"></script>  <script type="text/javascript" src="${base}/struts/jwa/js/validation.js"></script>  <script type="text/javascript">  $(document).ready(function() {      jQuery('#${parameters.id}').ajaxForm({          'success' : function(data, status, xhr, form) {              if(hasValidationErrors(data)) {                  showValidationErrors(data, form);              } else {                  location.href = form.attr('forward');              }          }      });  });  </script>  </#if>
1-3.classpath/template/jwa/js/validation.js

function hasValidationErrors(data) {      if(data.errors || data.fieldErrors)          return true;      else          return false;  }    function showValidationErrors(data, form) {      var formid = form.attr('id');      var actionErrorWrap = $('#'+form.attr('actionErrorId'));      var actionErrorWrapExist = actionErrorWrap.length > 0;      if(actionErrorWrapExist) {          actionErrorWrap.html('');      }            if(data.errors) {          for(var i in data.errors) {              if(!actionErrorWrapExist)                  alert(data.errors[i]);              else                  actionErrorWrap.append('<p>'+data.errors[i]+'</p>');          }      }            if(data.fieldErrors) {          for(var i in data.fieldErrors) {              var error = data.fieldErrors[i].toString();              var field = $('#'+formid+'_'+i);              var fieldErrorWrap = $('#'+field.attr('fieldErrorId'));              if(fieldErrorWrap.length > 0) {                  fieldErrorWrap.html(error);              } else if(actionErrorWrapExist) {                  actionErrorWrap.append('<p>'+error+'</p>');              } else {                  alert(error);              }          }      }  }


2.创建com.wogu.jwa.AjaxAction

package com.wogu.jwa;    import java.util.*;    import com.opensymphony.xwork2.ActionSupport;    public class AjaxAction extends ActionSupport  {      public static final String AJAX = "ajax";            private Map<String, Object> ajaxErrors = new HashMap<String, Object>();            public Map<String, Object> getAjaxErrors() {          Collection<String> errors = getActionErrors();          if(errors.size() > 0) {              ajaxErrors.put("errors", errors);          }                    Map<String, List<String>> fieldErrors = getFieldErrors();          if(fieldErrors.size() > 0) {              ajaxErrors.put("fieldErrors", fieldErrors);          }                    return ajaxErrors;      }  }

3.struts.xml

<?xml version="1.0" encoding="utf-8"?>  <!DOCTYPE struts PUBLIC      "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"      "http://struts.apache.org/dtds/struts-2.0.dtd">    <struts>      <package name="admin" extends="json-default" namespace="/admin">            <action name="login" class="indexAction">              <result>/WEB-INF/views/login.jsp</result>          </action>            <action name="dologin" class="loginAction">              <result name="ajax" type="json">                  <param name="root">ajaxErrors</param>              </result>              <result name="input">/WEB-INF/views/login.jsp</result>              <interceptor-ref name="jsonValidationWorkflowStack"/>          </action>      </package>  </struts>

4./WEB-INF/views/login.jsp

<%@ page pageEncoding="utf-8" contentType="text/html; charset=utf-8" %>  <%@ taglib prefix="s" uri="/struts-tags" %>  <!DOCTYPE html>  <html>  <head>   <title>struts+jquery+Ajax表单验证 - power by wogu</title>   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">   <link href="favicon.ico" rel="shortcut icon">   <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/struts/jwa/css/style.css">   <script type="text/javascript" src="${pageContext.request.contextPath}/struts/jwa/js/jquery-1.7.1.min.js"></script>  </head>  <body>  <s:form id="myform" theme="jwa" validate="true" actionErrorId="tip" namespace="/admin" action="dologin" method="post" forward="${pageContext.request.contextPath}/admin/index">  <div id="main">      <div id="login_box">          <ul>              <li>用户名:<s:textfield name="username"/></li>              <li>密 码:<s:textfield name="password"/></li>              <li style="padding-left:48px;">                  <s:submit value=" 登录 " cssClass="btn"/>                  <s:reset value=" 清除 " cssClass="btn"/>              </li>              <li style="padding-left:48px;"><a href="#"><img src="${pageContext.request.contextPath}/struts/jwa/images/top_qq_login1.gif" border="0" style="vertical-align:middle;"/></a></li>          </ul>          <div id="tip" style="color:#ffffff;line-height:20px;padding-top:20px;"/>      </div>  </div>  </s:form>  </body>  </html>

5.com.wogu.jwa.actions.LoginAction

package com.wogu.jwa.actions;    import com.wogu.jwa.AjaxAction;  import com.opensymphony.xwork2.ActionContext;    public class LoginAction extends AjaxAction  {      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;      }            public String execute() {          if(username.equals("test") && password.equals("123456")) {              ActionContext.getContext().getSession().put("userid", "1");          } else {              addActionError(getText("loginAction.user_or_password.error"));          }                    return AJAX;      }  }