SSH2 AJAX LoginDemo 項目添加驗證體系

Struts2 框架的驗證體系主要分爲:

  • action 中重寫 validate() 進行 action類全局校驗
  • action 中添加 validateXxx() 爲 Xxx() 方法專門做的前置校驗。(Strut2 利用反射自動映射)
  • 使用Struts2 驗證框架 進行校驗


我們在 LoginDemo 中對這幾種方法都會有舉例:

 

Struts2 數據提交的步驟是:

  • 校驗框架
  • validate()
  • validateXxx()
  • action()

 

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%@taglib prefix="sj" uri="/struts-jquery-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
 
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <sj:head locale="zh_CN" jqueryui="true" />
        <!-- AJAX 方式登錄 callback 函數響應 login.js -->
        <script type="text/javascript" src="js/login/login.js"></script>
        <!-- 載入樣式表 -->
        <link rel="stylesheet" type="text/css" href="css/style.css" />
        <title><s:text name="index.title" /></title>
    </head>
    <body>
        <div id="login_div">
            <form action="login-ajax/loginAjax.action" method="post" id="login_form">
                <fieldset class="login-fieldset">
                    <legend><s:text name="form.ajax.title" /></legend>
                    <label for="input_username" class="login-label">
                        <s:text name="text.label.username" />
                        <span id="user_username_error" class="error-message"></span>
                    </label>
                    <span class="input-span-block">
                        <input type="text" id="input_username" name="user.userName" />
                    </span>
                    <label for="input_userpass" class="login-label">
                        <s:text name="text.label.userpass" />
                        <span id="user_userpass_error" class="error-message"></span>
                    </label>
                    <span class="input-span-block">
                        <input type="password" id="input_userpass" name="user.userPass" />
                    </span>
                    <span class="button-span-block">
                        <sj:submit id="login_submit"
                                targets="result_message"
                                validate="true"
                                validateFunction="customLoginValidate"
                                onBeforeTopics="clearFieldErrors"
                                onSuccessTopics="success"
                                dataType="json"
                                value="%{getText('button.label.loginbyajax')}" />
                    </span>
                </fieldset>
            </form>
        </div>
        <div id="result_message" class="error-message"></div>
    </body>
</html>
 

login.js

//JSON 格式錯誤返回值中,KEY 中保存的是 input name的值,自定義函數進行同輸出錯誤信息元素的映射
//本例中將 "user.userName" 轉化爲 "#user_username_error"
function formatErrorElementId(value) {
    var elem = value.toLowerCase();
    elem = elem.replace(/\./g , "_");
    elem += "_error"
    elem = "#"+elem;
    return elem;
}
 
//處理 JSON 格式的 validate 失敗返回值
function customLoginValidate(form , errors) {
    if (errors.fieldErrors) {
        $.each(errors.fieldErrors , function(key,value) {
            var elem = formatErrorElementId(key);
            if (elem) {
                $(elem).html(value[0]);
            }
        });
    }
}
 
//清除前次留下的錯誤信息
$.subscribe("clearFieldErrors", function() {
    $("#user_username_error").html("");
    $("#user_userpass_error").html("");
});
 
//登錄陳功後,輸出的登錄狀態信息
$.subscribe("success" , function(event) {
    $("#result_message").html(event.originalEvent.data.loginMessage);
});
 

style.css

body {
    margin: 0;
    padding: 0;
    text-align: center;
    font-family: Georgia,'Times New Roman',times,serif;
}
 
#login_div {
    width:300px;
    margin: 2em auto;
    padding: 0.5em;
}
 
#login_div .error-message {
    font-size: 0.8em;
    font-style: italic;
    color: red;
    font-weight: bold;
}
 
#login_div .login-fieldset {
    padding: 0.3em;
    text-align: left;
    font-weight: bold;
}
 
#login_div .login-label {
    display: block;
}
 
#login_div .input-span-block {
    display: block;
}
 
#login_div .button-span-block {
    display: block;
    text-align: right;
}
 
#input_username , #input_userpass {
    width: 98%;
}
 
#login_submit {
    margin: 0.3em 0;
    padding: 0.3em 1em;
    font-weight: bold;
}
 
#result_message {
    width: 400px;
    margin: 0 auto;
    padding: 1em;
    font-weight: bold;
    font-size: 1.5em;
    color: red;
}

 

 

LoginAction.java

 

package com.track2web.demo.action;
 
import com.opensymphony.xwork2.ActionSupport;
import com.track2web.demo.entity.User;
import com.track2web.demo.service.IUserService;
 
public class LoginAction extends ActionSupport {
 
    //定義登錄是否成功狀態,驗證錯誤信息國際化信息常量
    public static final String LOGIN_STATUS_SUCCESS = "login.status.message.success";
    public static final String LOGIN_STATUS_FAIL = "login.status.messsage.fail";
    public static final String USERNAME_VALIDATE_LENGTH = "input.minlenth.username";
    public static final String USERPASS_VALIDATE_LENGTH = "input.minlenth.userpass";
 
    //user對象接受頁面傳值
    private User user;
    //loginMessage 回傳登錄是否成功的狀態
    private String loginMessage;
    //IOC接口
    private IUserService userService;
 
    public User getUser() {
        return user;
    }
 
    public void setUser(User user) {
        this.user = user;
    }
 
    public String getLoginMessage() {
        return loginMessage;
    }
 
    public void setLoginMessage(String loginMessage) {
        this.loginMessage = loginMessage;
    }
 
    public IUserService getUserService() {
        return userService;
    }
 
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
 
    /**
     * action 全局驗證
     */
    @Override
    public void validate() {
        if (this.user.getUserName().length()<4) {
            addFieldError("user.userName", getText(USERNAME_VALIDATE_LENGTH));
        }
    }
 
    /**
     * 通過反射(Reflection)調用 validateLoginAjax()方法(爲 loginAjax 方法驗證數據)
     */
    public void validateLoginAjax() {
        if (this.user.getUserPass().length()<4) {
            addFieldError("user.userPass", getText(USERPASS_VALIDATE_LENGTH));
        }
    }
 
    /**
     * Ajax 方式所調用的 Action 方法
     * @return 返回調用成功信號
     */
    public String loginAjax() {
        //將 登錄信息保存至 user 屬性,如果校驗失敗,user 屬性值爲 NULL
        this.user = this.userService.login(user);
        if (user==null) {
            this.loginMessage = getText(LOGIN_STATUS_FAIL);
        }
        else {
            this.loginMessage = getText(LOGIN_STATUS_SUCCESS);
        }
        return SUCCESS;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章