Day 20 - Spring Boot & Session

Session 介绍

Session 是储存在Server (服务器)端的资料,当Client 端第一次发送请求时,Server 自动产生一个Session 和一个用来辨识Session 的唯一值Session ID,回应时再将Session ID 回传给Client 端储存,这样当Client 端第二次请求时,只需将前一次回应的Session ID 一并发送给Server 端,Server 就可以透过请求中的Session ID,与Server 保存的Session ID 进行比对,进而取得这个用户专属的Session 资料。
一般情况下,Server 都会在默认时间(30分钟)内保存这个Session,过了保存时间便会销毁Session 资料。

用途

用途与Cookie 大致相同,都是为了保存使用者的资讯,Session ID 的实现方法也是使用Cookie 来完成,Server 端透过设定Cookie 的方法将Session ID 发送给Clinet 端进行保存。

缺点

Session 是将资料储存在Server 端,会占用Server 的资源,当使用者一多或是资料过大,都会严重影响Server 的效能。

Session 实作

设置Session

若要在Spring Boot 设置Session,我们可以使用HttpSessionsetAttribute() 方法,与HttpServletResponse 的addCookie() 只能储存一个字串相比,HttpSession 的setAttribute() 方法可以储存一个物件。

// 改写doLogin() 方法
@RequestMapping(value = "/login", method = {RequestMethod.POST})
public String doLogin(
		@ModelAttribute MemberAccount memberAccount, 
		Model model,
		HttpSession session) {
	
	Member result = memberAccountService.login(memberAccount);
	if(result == null) {
		logger.warn(memberAccount.getAccount() + "尝试登入系统");
		return "redirect:login";
	}

	// 设置Session
	session.setAttribute("MemberSession", result);

	logger.info(result.getName() + "登入系统");
	return "redirect:information";
}

读取Session

Spring Boot 读取Session 的方法有两种,一种是使用HttpSession 的getAttribute() 方法,另一种则是@SessionAttribute 注释,这边先使用@SessionAttribute 注释。

// 改写information() 方法
@RequestMapping(value = "/information", method = RequestMethod.GET)
public String information(@SessionAttribute("MemberSession") Member member) {

	System.err.println(member.toString());
	
	return "information";
}

删除Session

@RequestMapping(value = "/logout", method = {RequestMethod.GET})
public String logout(HttpSession session, SessionStatus sessionStatus) {
	
	if(session.getAttribute("MemberSession") != null){
		session.removeAttribute("MemberSession");
		sessionStatus.setComplete();
	}
	
	return "redirect:login";
}

Github

新增Session 设置、读取、删除功能


<<:  #Day20--那些年,我们一起犯的傻

>>:  自动化测试,让你上班拥有一杯咖啡的时间 | Day 21 - drag and drop 的用法

DAY 25 Full Screen Modal - Follow Us

这个部分主要是 social media 的区块,会用到 fontawesome 上的 icon 们...

1. STM32-STM32CubeIDE 安装/程序码补齐功能

STM32CubeIDE安装 首先可以到官网下载对应系统的安装档 STM32官网 选择对应系统下载後...

Day 11 ( 中级 ) 拍手换图案 ( 二代板 )

拍手换图案 ( 二代板 ) 教学原文参考:拍手换图案 ( V2 ) 这篇文章是针对 micro:bi...

Azure Retail Prices REST API 分析全 Azure 服务价格差异 - JSON 转 Excel版本

笔者有以下分析需求 想知道同样服务所有区域的价格从低到高 想知道同样服务那些区域有支援 这边可以使用...

Day28:每天一个小练习 - JS30-13-Slide in on Scroll

参考资料: Alex老师教学 PJCHENder笔记 卷动出现图片。 题目预设的过滤效果,避免多次触...