세션 개요
- 클라이언트와 웹 서버 간 상태를 지속적으로 유지하는 방법
- 웹 서버에 저장되어 웹 서버에서만 접근이 가능하므로 보안 유지에 유리하고 데이터를 저장하는데 한계가 없음
- 웹 서버에 존재하는 객체 이기 때문에 브라우저 마다 하나씩 존재하게 되어 서비스를 제공받는 구분 단위가 된다.
세션 내장 객체 메소드
<index.jsp>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html><html><head></head>
<body>
<form action="session_process.jsp" method="POST">
<p>아이디 : <input type="text" name="id"></p>
<p>비밀번호 : <input type="text" name="passwd"></p>
<p><input type="submit" value="전송"></p>
</form>
</body>
</html>
<session_process.jsp>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html><head></head><body>
<%
String userId = request.getParameter("id");
String userPw = request.getParameter("passwd");
if( userId.equals("admin") && userPw.equals("1234")){
session.setAttribute("userId", userId);
session.setAttribute("userPw", userPw);
out.println("<p>세션 설정이 성공했습니다</p>");
out.println(userId + "님 환영합니다.");
}else {
out.println("세션설정이 실패했습니다.");
}
%>
</body></html>
- 세션 생성: void setAttribute(String name, Object value)
- 동일한 세션 속성 이름으로 세션을 생
- 세션 정보 얻기
- session.getAttribute(”sessionId”);
- session.getAttributeNames();
- 세션 정보 삭제: session.invalidate();
- 세션 유효시간 설정: session.setMaxInactiveInterval(int time);
쿠키 개요
- 클라이언트와 웹 서버 간 상태를 지속적으로 유지하는 방법
- 세션과 다른 점: 웹 서버가 아닌 클라이언트에 저장
- 세션과 비교하였을때 보안적으로 약하다.
- 웹 서버 부하를 줄일 수 있다
- 저장 크기는 4KB 이하이다.
쿠키 동작 과정
- 생성: 웹 서버에서 먼저 생성, 생성된 쿠키는 응답 데이터에 함께 저장되어 웹 브라우저에 저장
- 저장: 웹 브라우저는 응답 데이터에 포함된 쿠키를 쿠키 저장소에 보관, 종류에 따라 메모리나 파일로 저장
- 전송: 저장된 쿠키를 요청이 있을 때마다 서버에 전송
쿠키 내장 메소드
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cookie Setting Page</title>
</head>
<body>
<%
String cookieName = "TestCookie";
String cookieValue = "Cookie Value";
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setMaxAge(60*60*24); // 쿠키의 유효기간을 24시간으로 설정
response.addCookie(cookie); // 쿠키를 클라이언트에게 보냄
%>
<p>Cookie has been set.</p>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cookie Reading Page</title>
</head>
<body>
<%
Cookie[] cookies = request.getCookies(); // 모든 쿠키를 가져옴
if (cookies != null) {
for (Cookie cookie : cookies) { // 모든 쿠키를 순회
String name = cookie.getName();
String value = cookie.getValue();
out.println("<p>" + name + " : " + value + "</p>"); // 쿠키의 이름과 값을 출력
}
}
%>
</body>
</html>
- 쿠키 생성: Cookie cookieId = new Cookie("userId", userId);
- 쿠키 정보 얻기: Cookie[] cookies = request.getCookies();
- 쿠키 삭제: cookie.setMaxAge(0);
쿠키 세션 차이

'Development > JSP' 카테고리의 다른 글
| 예외 처리, 필터 (0) | 2023.05.21 |
|---|---|
| 다국어 처리& 시큐리티 (0) | 2023.05.18 |
| 유효성 검사 (0) | 2023.05.10 |
| 파일 업로드 (0) | 2023.05.09 |
| 내장 객체(Implicit Object) (0) | 2023.04.19 |