SpringMVC使用session實現簡單登錄

1.首先爲了能直觀地在jsp頁面體現session的內容,我使用了jstl表達式,首先在pom.xml中引入jstl的依賴

		<!-- jstl所需要的依賴 -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

2.編寫登錄界面以及登錄成功界面

登錄界面

<%@ page contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html >
<html>
<head>
<meta charset="utf-8">
<title>用戶登錄</title>
</head>
<body>
	<form action="login" method="post">
		<input type="text" name="uname" /><br/><br/>
		<input type="password" name="pwd" /><br/><br/>
		<input type="submit" value="登錄"><br/><br/>
	</form>
</body>
</html>

登錄成功界面

<%@ page contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!-- 引入jstl庫 -->
<!DOCTYPE html >
<html>
<head>
<meta charset="utf-8">
<title>成功</title>
</head>
<body>
	<h1>${sessionScope.user.uname }登錄成功!!!</h1>
	<h2>歡迎您,${sessionScope.uname }</h2>
</body>
</html>

3.編寫請求處理類以及實體類

實體類

package com.yc.entity;

public class User {
	private String uname;
	private String pwd;
	
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
	public String toString() {
		return "User [uname=" + uname + ", pwd=" + pwd + "]";
	}
}

請求處理類

package com.yc.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.yc.entity.User;

@Controller
@SessionAttributes({"user","uname"})
public class LoginController {

	@RequestMapping("/login")
	public String login(User user,ModelMap map) {
		//user會自己注入session中
		//將uname放入session作用域中,這樣轉發頁面也可以取到這個數據。
		map.addAttribute("uname", user.getUname());
		return "loginSuccess";
	}
}

4.運行測試



OK,到現在我們利用session實現的用戶登錄已經可以了大笑

發佈了36 篇原創文章 · 獲贊 4 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章