Jsp登錄邏輯流程

引言

對於Jsp的登錄邏輯做一個簡要概述,方便以後回憶。以下代碼基於Spring框架。

邏輯流程

登錄頁面的login.jsp主要代碼,關鍵是在form中引入action去調用後端的接口

<form id="kvm_login_form" class="form-signin" action="loginCheck.do" method="post"
			onsubmit="return CheckToken();">
			<h2 class="form-signin-heading" id="kvm_login">Login</h2>
			<input type="text" class="input-block-level" id="username" name="username" placeholder="User Name">
			<input type="password" class="input-block-level" id="kvm_password" name="password" placeholder="Password">
			<button class="btn btn-large btn-primary" id="submit" type="submit">Sign in</button>
		</form>

其中CheckToken是響應提交後處理,具體代碼如下

<script>
		function CheckToken() {
			//清除原先的token
			sessionStorage.removeItem("authToken");
			$.ajax({
				type: 'post',
				url: '../api/authentication',
				contentType: 'application/x-www-form-urlencoded',
				async: false,
				data: $('#kvm_login_form').serialize(),
				success: function (data) {
					//記錄token到sessionStorage
					sessionStorage.authToken = data.authToken;
				},
				error: function (data) {
					return false;
				}
			});
		}
	</script>

後端提供的接口loginCheck.do

@RequestMapping(value = "/loginCheck.do",method = RequestMethod.POST)
    public String login(@ModelAttribute("user") Account account){
        String password = "";
        try {
            password = Md5Base64.md5(account.getPassword());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Account account2 = accountService.getAccountByName(account.getUsername(), password);
        if (account2 != null) {
            return "redirect:profile.do";
//            return "redirect:profile.do?id=" + account2.getId();
        } else {
            return "redirect:login.do"; // 重定位到login.jsp
        }
    }

通過後端重定位到另一個接口

@RequestMapping(value = "profile.do",method = RequestMethod.GET)
    public String kvm(@RequestParam("id") int id,ModelMap model){
        Account account = accountService.getAccountById(id);
        model.addAttribute("account", account);
        return "profile"; // 映射到profile.jsp文件
    }

注意,上面接口中request的modelmap中保存了用戶信息,方便profile.jsp獲取用戶信息【${account.username}】,具體如下

<a class="brand" href="#">
					<strong>User Name [${account.username}]</strong>
					<div class="menu">

					</div>
				</a>

以上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章