[Spring] Session, Cookie

JH·2023년 4월 28일

Java

목록 보기
17/21

1. TIL

POSTMAN : 요청과 응답 결과 확인 테스트를 위한 도구
https://www.postman.com/downloads/

Session을 얻는 방법 2가지

1. Controller의 파라미터로 HttpSession session을 받음

2. @SessionAttributes({"grade"}) Session에 대한 제어가 Spring Context로 넘어감
Controller의 파라미터로 SessionStatus status를 받음 (spring context가 관리하는 세션)



Cookie 흐름 : index,jsp → SessionCookieController → cookieView

Session 흐름 : index,jsp → SessionCookieController → sessionView → SessionCookieController (gradeDelete, sessionDelete)

SessionDTO 흐름 : index,jsp → SessionCookieController → sessionView → SessionCookieController (sessionDTOdelete)

DTO

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@ToString
public class Student {
	private String name;
	private int age;
}

1. index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
	<%
		/* Cookie */
		Cookie cookie1 = new Cookie("id", "dev");
		cookie1.setMaxAge(60 * 60 * 24);
		
		response.addCookie(cookie1);
		
		/* Session */
		session.setAttribute("name", "dev");
		session.setAttribute("age", 28);
	%>
	<h1>Cookie, Session</h1>
	<a href="cookieTest.do">1. CookieTest.do</a><hr>
      
	<a href="sessionTest1.do">2. SessionTest1.do</a><hr>
      
	<a href="sessionTest2.do?name=spring&age=26">3. SessionTest2.do(DTO)</a>
</body>
</html>

2. SessionCookieController

@Controller
@SessionAttributes({"grade",  "student"}) // Session에 대한 제어가 Spring Context로 넘어감
public class SessionCookieController {
	@RequestMapping(value = "/cookieTest.do", method = RequestMethod.GET)
	public String cookieTest(@CookieValue("id") String id) {
		return "cookieView";
	}
	
	@RequestMapping(value = "/sessionTest1.do", method = RequestMethod.GET)
	public String sessionTest1(@SessionAttribute("name") String name,
							   @SessionAttribute("age") int age, 
							   HttpSession session) {
		session.setAttribute("grade", "junior");
		return "sessionView";
	}
	
	@RequestMapping(value = "/gradeDelete.do", method = RequestMethod.GET)
	public String gradeDelete(HttpSession session, SessionStatus status) {
		System.out.println(session.getAttribute("grade"));
		
		// HttpSession
		if (session != null) {
			session.removeAttribute("grade");
		}
		
		// SessionStatus
		status.setComplete();
		
		return "sessionView";
	}
	
	@RequestMapping(value = "/sessionDelete.do", method = RequestMethod.GET)
	public String sessionDelete(HttpSession session) {
		
		if (session != null) {
			session.invalidate();			
		}
		return "sessionView";
	}
	
	// DTO 전달
	@RequestMapping(value = "/sessionTest2.do", method = RequestMethod.GET)
	public String sessionTest2(Student student) {
		System.out.println(student);
		return "sessionDTOView";
	}
	
	@RequestMapping(value = "/sessionDTODelete.do", method = RequestMethod.GET)
	public String sessionDTODelete(SessionStatus status) {
		status.setComplete();
		return "sessionDTOView";
	}
}

cookie.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>cookieView</title>
</head>
<body>
	<h1>Cookie View</h1>
	${ cookie.id } - ${ cookie.id.name } - ${ cookie.id.value }
</body>
</html>

sessionView.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Session View</title>
</head>
<body>
	<h1>Session View</h1>
	name : ${sessionScope.name} <br>
	age: : ${sessionScope.age}<br>
	grade : ${sessionScope.grade}<br>
    
    <hr>
    <!-- SessionCookieController -->
	<a href="gradeDelete.do">grade 삭제</a><hr>
	<a href="sessionDelete.do">모든 세션 삭제</a>
</body>
</html>

sessionDTOView.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SessionDTOView</title>
</head>
<body>
	<h1>SessionDTOView</h1>
	name : ${sessionScope.student.name}<br>
	age : ${sessionScope.student.age} <br>

	<hr/>
	<a href="sessionDTODelete.do">sessionDTO 삭제</a>
</body>
</html>



B. Login Session

Login 흐름 : HomeController → home.jsp → LoginController → login.jsp → LoginController(login, logout) → home.jsp

1. HomeController

@Controller
public class HomeController {
	@RequestMapping(value = "/home", method = RequestMethod.GET)
	public String home() {
		return "home";
	}	
}

2. home.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page pageEncoding="UTF-8"%>
<html>
<head>
	<title>Home</title>
</head>
<body>
<h1>
	Hello world!  
</h1>
<div align="center">
	<!-- 로그인 버튼 클릭 시, login.jsp -->
	<c:if test="${empty sessionScope.userId }">
		<input type="button" value="로그인" onclick="location.href='/login.do'">
	</c:if>
	
	<c:if test="${not empty sessionScope.userId }">		
		${sessionScope.userId}님 &nbsp;&nbsp;
		<input type="button" value="로그아웃" onclick="location.href='/logout.do'">
	</c:if>
</div>
<c:if test="${not empty sessionScope.userId}">
	<P align="center">  The time on the server. </P>
</c:if>
</body>
</html>

3. LoginController

@Controller
public class LoginController {
	
	@RequestMapping(value = "/login.do", method = RequestMethod.GET)
	public String loginForm() {
		return "login";
	}
	
	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public String login(@RequestParam("id") String id, 
						@RequestParam("pw") String pw,
						HttpSession session) {
		if("dev".equals(id) && "it".equals(pw)) {
			session.setAttribute("userId", id);
		}
		return "home";
	}
	
	@RequestMapping(value = "/logout.do", method = RequestMethod.GET)
	public String logout(HttpSession session) {
		
		if(session != null) {
			session.invalidate();
		}
		return "home";
	}
}

4. login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
	<form method="POST" action="login.do">
		id : <input type="text" id="" name="id" placeholder="id 입력"/> <br />
		pw : <input type="password" id="" name="pw" placeholder="pw 입력"/> <br />
		<input type="submit" value="로그인"/>
	</form>
</body>
</html>



2. 에러

session이나 model을 통해 데이터를 얻어와야 하는데 못받는 경우가 종종 있었음
주말 동안 해결해야할 것으로 보임


3. 보완 해야 할 것

url 전환 시 특정 데이터를 페이지에 전달하려면 model을 사용하는게 맞는건가 아직 모르겠음

request, session을 통해서도 전달할 수 있어서 유지되어야 하는 데이터를 어떤 타입으로 사용해야하는 것에 보안이 필요함


4. 느낀점

Spring은 참 편리하면서 어렵고 손이 많이 가는 것 같다.
하나 하나 배울 때와 배우고나서 최종 구현할 때 갭이 이렇게 클 줄 몰랐다.

profile
잘해볼게요

0개의 댓글