Hello, Dino
Cookie / Session 본문
Cookie와 Session을 사용하는 이유는? 🤔
HTTP 프로토콜의 특징이자 약점을 보안하기 위하여 !
1. 비연결지향 (Connectionless)
Http 프로토콜은 클라이언트가 요청했을 때, 그에 맞는 응답을 보낸 후 연결을 끊는다.
why? 수천명의 클라이언트가 요청을 보낼 때, 그 연결을 계속 유지하면 서버 부하 가능성 有
2. 상태정보 유지 X (Stateless)
클라이언트와 이전 통신에서 데이터를 주고 받았어도, 그 이후 통신에서는 이전 데이터를 유지하지 않음
때문에 서버와 연결이 끊어진 후에도 데이터 유지가 필요할 때 Cookie와 Session이 필요하다.
Cookie🍪
: Http에서 Client State 정보를 웹브라우저에 저장하였다가 필요시 정보를 참조하거나 재사용한다.
Cookie 특징
1. 이름, 값, 만료일, 경로 정보로 구성되어 있다.
2. 클라이언트에 총 300개의 쿠키를 저장 할 수 있다.
3. 하나의 도메인 당 20개의 쿠리를 가질 수 있다.
4. 하나의 쿠키는 4KB까지 저장이 가능하다.
Cookie Life Cycle
1. 브라우저에서 웹 페이지 접속
2. 웹 서버 쿠키 생성
2. HTTP 요청 전송 시 생성한 쿠키에 정보를 담아 클라이언트에게 전달한다.
클라이언트는 요청한 웹페이를 받으면서 쿠키를 클라이언트 로컬에 저장
3. 클라이언트 재 요청시 웹페이지 요청과 함께 쿠키 값 전송
4. 지속적으로 로그인 정보를 가지고 있는 것처럼 사용
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
// Login 전 로그인 관련 Cookie 정보가 있는지 확인
Cookie[] cookies = request.getCookies();
System.out.println("Cookies : " + cookies);
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("memberId")){
response.sendRedirect("loginOK.jsp");
}
}
}
%>
<form action="loginCon" method="post">
ID : <input type="text" name="memberId"><br>
PW : <input type="password" name="memberPw0"><br>
<input type="submit" value="login">
</form>
</body>
</html>
loginCon.servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
// get parameter
String memberId = request.getParameter("memberId");
String memberPw = request.getParameter("memberPw");
writer.print("ID: " + memberId);
writer.print("PW: " + memberPw);
// get cookies
Cookie[] cookies = request.getCookies(); // 배열 형식으로 return
Cookie cookie = null;
for (Cookie item : cookies) {
System.out.println(item.getName() + ": " + item.getValue());
if(item.getName().equals("memberId")) {
cookie = item;
}
}
if(cookie == null) {
System.out.println("Cookie is null");
// set cookie
cookie = new Cookie("memberId", memberId);
}
// response에 cookie 추가
response.addCookie(cookie);
cookie.setMaxAge(60*60);// Cookie 유지 최대 시간
response.sendRedirect("loginOK.jsp");
}
loginOK.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
// jsp Cookie 접근
Cookie[] cookies = request.getCookies();
for(Cookie cookie : cookies){
out.print("name: " + cookie.getName() + "<br>");
out.print("value: " + cookie.getValue() + "<br>");
out.print("-------------------------------------------");
}
%>
</body>
</html>
Session 💡
: Http에서 Web Container의 상태를 유지하기 위한 정보를 Web Server에 저장한다.
Session 특징
1. 웹 서버에 저장되는 쿠키
2. 브라우저를 닫거나, 서버에서 세션을 삭제했을 때 삭제되므로, 쿠키보다 비교적 보안이 좋다
3. 저장 데이터에 제한이 없다.
4. 각 클라이언트 고유 Session ID를 부여한다.
Session Life Cycle
1. 브라우저에서 웹 페이지 접속
2. 서버는 클라이언트의 Request header 필드인 cookie를 확인하여 클라이언트가
해당 session id를 보냈는지 확인한다.
3. session id가 존재하지 않는다면, 서버는 session id를 생성해 클라이언트에게 돌려준다.
4. 서버는 클라이언트에게 돌려준 session id를 쿠리를 사용하여 서버에 저장한다.
* cookie name : JESSIONID
5. 클라리언트 재 접속시, 전달받은 쿠키를 이용하여 session id 값을 서버에 전달한다.
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
// login전 login관련 session 값이 있는지 확인
if(session.getAttribute("memeberId") != null){
response.sendRedirect("loginOK.jsp");
}
%>
<form action="LoginCon" method="post">
ID : <input type="text" name="memberId"><br>
PW : <input type="password" name="memberPw"><br>
<input type="submit" value="login">
</form>
</body>
</html>
loginCon.servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
// get parameter
String memberId = request.getParameter("memberId");
String memberPw = request.getParameter("memberPw");
writer.print("ID: " + memberId);
writer.print("PW: " + memberPw);
// get session
HttpSession session = request.getSession();
// set session
session.setAttribute("memberId", memberId);
response.sendRedirect("loginOK.jsp");
}
loginOK.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
// jsp session 접근
session = request.getSession();
out.print("member ID: " + session.getAttribute("memberId"));
%>
<form action="logoutCon" method="post">
<input type="submit" value="logout">
</form>
</body>
</html>
logoutCon.servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
// session 종료
session.invalidate();
response.sendRedirect("login.jsp");
}
Cookie와 Session의 차이점은? 🤔
Cookie | Session | |
저장 위치 | client(web browser) | web server |
저장 형식 | text | object |
만료 시점 | cookie 유지 최대 시간 이후 | 브라우저 종료 시 |
사용하는 자원 | 클라이언트 리소스 | 웹 서버 리소스 |
용량 제한 |
총 300개 하나의 도메인 당 200개 하나의 쿠키 당 4KB |
서버가 허용하는 한 용량 제한 없음 |
속도 |
빠르다 |
느리다 |
보안 |
보안 취약 |
보안 |
Session만 사용하면 되지 않을까?🤔
Session은 web server에 저장이 되고, 서버 자원을 사용하기 때문에 사용자가 많은 경우 소모되는 서버 자원이 상당하다.
때문에 이러한 자원 관리 차원에서 cookie와 session을 적절한 요소 및 기능에 병행 사용하여,
서버 자원의 낭비를 방지하며 웹 사이트의 속도를 높일 수 있다.
Reference
https://hahahoho5915.tistory.com/32
쿠키(Cookie), 세션(Session) 특징 및 차이
개요 > 쿠키(Cookie), 세션(Session) 각각 특성 및 차이 확실히 분류하기 메모 1. 공통점 : 웹 통신간 유지하려는 정보(ex:로그인 정보 등)를 저장하기 위해 사용하는 것(?) 2. 차이점 : 저장위치, 저장형식, 용..
hahahoho5915.tistory.com
https://jeong-pro.tistory.com/80
'Web > JSP' 카테고리의 다른 글
Page 이동 방식 (Forward / Redirect) (0) | 2020.03.10 |
---|---|
한글 처리 (encoding) (0) | 2020.03.10 |
Servlet 생성부터 Servlet Mapping까지 🏃♀️ (0) | 2020.01.10 |
JSP 개발 환경 설정 (0) | 2020.01.07 |