struts2+jquery+ajax表單驗證

一、常見問題:

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

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

 

2.每驗證一次,錯誤信息就累加一次,出現重復?

解決:如果你整合瞭spring,請將相應bean的singleton設為false(spring中的bean默認為單例模式,導致前次驗證產生的錯誤信息一直存在)

 

二、Demo1:使用xhtml主題的表單驗證

1.struts.xml

[html]  

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

<!DOCTYPE struts PUBLIC  

    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  

    "https://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

[html]  

<%@ 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

[java] 

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

[html]  

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "https://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

[plain] view plaincopy

parent = simple  

 

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

[html]  

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

[javascript]  

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

[java] 

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

[html] 

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

<!DOCTYPE struts PUBLIC  

    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  

    "https://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

[html]  

<%@ 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">  

<p id="main">  

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

        <p id="tip" style="color:#ffffff;line-height:20px;padding-top:20px;"/>  

    </p>  

</p>  

</s:form>  

</body>  

</html>  

 

5.com.wogu.jwa.actions.LoginAction

[java]  

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;  

    }  

}  

 

發佈留言