1. 程式人生 > >SpringMVC使用session實現簡單登入

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實現的使用者登入已經可以了大笑