반응형
세션(HttpSession)
: 클라이언트로부터 오는 요청을 하나의 상태로 보고, 그 상태를 일정하게 유지하는 기술
- 세션의 특징
- 세션을 통해서 사용자(브라우저)별로 구분하여 정보를 관리할 수 있다.(세션ID 이용)
- 쿠키를 사용할 때보다 보안이 향상된다. (정보가 서버에 저장되기 때문)
- 세션 객체를 가져오는 방법
HttpSession session = req.getSession(boolean값);
// boolean값 : true 인 경우 => 세션객체가 존재하지 않으면 새로 생성된다.
// false 인 경우 => 세션객체가 존재하지 않으면 null을 리턴함.
- 세션 객체 삭제 처리 방법
1. invalidate() 메서드 호출
2. setMaxInactiveInterval(int interval) 메서드 호출
3. web.xml 의 <session-config> 설정하기 (분단위)
세션 가져오기
package kr.or.ddit.basic;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.SeekableByteChannel;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class T05ServletSessionTest extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 세션 객체를 가져오는데 없으면 새로 생성한다.
HttpSession session = req.getSession(true);
// 생성시간 가져오기
Date createTime = new Date(session.getCreationTime());
// 마지막 접근시간 가져오기
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "재방문을 환영합니다.";
int visitCnt = 0; // 방문횟수
String userId = "pc10"; // 사용자ID
if(session.isNew()) { // 세션이 새로 만들어졌는지 확인...
title = "처음 방문을 환영합니다.";
session.setAttribute("userId", userId);
} else {
visitCnt = (Integer) session.getAttribute("visitCnt");
visitCnt++; // 방문횟수 누적
userId = (String) session.getAttribute("userId");
}
session.setAttribute("visitCnt", visitCnt);
///////////////////////////////////////////////////
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<!doctype html><head><title>" + title + "</title></head>"
+ "<body>"
+ "<h1 align=\"center\">" + title + "</h1>"
+ "<h2 align=\"center\">세션 정보</h2>"
+ "<table border=\"1\" align=\"center\">"
+ "<tr bgcolor=\"orange\"><th>구분</th><th>값</th></tr>"
+ "<tr><td>세션ID</td><td>" + session.getId() + "</td></tr>"
+ "<tr><td>생성시간</td><td>" + createTime + "</td></tr>"
+ "<tr><td>마지막 접근시간</td><td>" + lastAccessTime + "</td></tr>"
+ "<tr><td>사용자 ID</td><td>" + userId + "</td></tr>"
+ "<tr><td>방문횟수</td><td>" + visitCnt + "</td></tr>"
+ "</table></body></html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
세션 객체 삭제 처리
- invalidate() 메서드 호출
package kr.or.ddit.basic;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.SeekableByteChannel;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class T05ServletSessionTest extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 세션 객체를 가져오는데 없으면 새로 생성한다.
HttpSession session = req.getSession(true);
// 생성시간 가져오기
Date createTime = new Date(session.getCreationTime());
// 마지막 접근시간 가져오기
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "재방문을 환영합니다.";
int visitCnt = 0; // 방문횟수
String userId = "pc10"; // 사용자ID
if(session.isNew()) { // 세션이 새로 만들어졌는지 확인...
title = "처음 방문을 환영합니다.";
session.setAttribute("userId", userId);
} else {
visitCnt = (Integer) session.getAttribute("visitCnt");
visitCnt++; // 방문횟수 누적
userId = (String) session.getAttribute("userId");
}
session.setAttribute("visitCnt", visitCnt);
session.invalidate(); // 세션 무효화시키기
///////////////////////////////////////////////////
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<!doctype html><head><title>" + title + "</title></head>"
+ "<body>"
+ "<h1 align=\"center\">" + title + "</h1>"
+ "<h2 align=\"center\">세션 정보</h2>"
+ "<table border=\"1\" align=\"center\">"
+ "<tr bgcolor=\"orange\"><th>구분</th><th>값</th></tr>"
+ "<tr><td>세션ID</td><td>" + session.getId() + "</td></tr>"
+ "<tr><td>생성시간</td><td>" + createTime + "</td></tr>"
+ "<tr><td>마지막 접근시간</td><td>" + lastAccessTime + "</td></tr>"
+ "<tr><td>사용자 ID</td><td>" + userId + "</td></tr>"
+ "<tr><td>방문횟수</td><td>" + visitCnt + "</td></tr>"
+ "</table></body></html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
- setMaxInactiveInterval(int interval) 메서드 호출
package kr.or.ddit.basic;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.SeekableByteChannel;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class T05ServletSessionTest extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 세션 객체를 가져오는데 없으면 새로 생성한다.
HttpSession session = req.getSession(true);
// 생성시간 가져오기
Date createTime = new Date(session.getCreationTime());
// 마지막 접근시간 가져오기
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "재방문을 환영합니다.";
int visitCnt = 0; // 방문횟수
String userId = "pc10"; // 사용자ID
if(session.isNew()) { // 세션이 새로 만들어졌는지 확인...
title = "처음 방문을 환영합니다.";
session.setAttribute("userId", userId);
} else {
visitCnt = (Integer) session.getAttribute("visitCnt");
visitCnt++; // 방문횟수 누적
userId = (String) session.getAttribute("userId");
}
session.setAttribute("visitCnt", visitCnt);
session.setMaxInactiveInterval(30);
///////////////////////////////////////////////////
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<!doctype html><head><title>" + title + "</title></head>"
+ "<body>"
+ "<h1 align=\"center\">" + title + "</h1>"
+ "<h2 align=\"center\">세션 정보</h2>"
+ "<table border=\"1\" align=\"center\">"
+ "<tr bgcolor=\"orange\"><th>구분</th><th>값</th></tr>"
+ "<tr><td>세션ID</td><td>" + session.getId() + "</td></tr>"
+ "<tr><td>생성시간</td><td>" + createTime + "</td></tr>"
+ "<tr><td>마지막 접근시간</td><td>" + lastAccessTime + "</td></tr>"
+ "<tr><td>사용자 ID</td><td>" + userId + "</td></tr>"
+ "<tr><td>방문횟수</td><td>" + visitCnt + "</td></tr>"
+ "</table></body></html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
- web.xml 의 <session-config> 설정하기 (분단위)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>ServletTest</display-name>
<servlet>
<servlet-name>T05ServletSessionTest</servlet-name>
<servlet-class>kr.or.ddit.basic.T05ServletSessionTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>T05ServletSessionTest</servlet-name>
<url-pattern>/T05ServletSessionTest</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
</web-app>
반응형
'자바' 카테고리의 다른 글
[Java 고급] 30장 서블릿 예시 (0) | 2024.02.22 |
---|---|
[Java 고급] 29장 서블릿 컨텍스트, 필터, 리스너 (0) | 2024.02.22 |
[Java 고급] 27장 쿠키 (0) | 2024.02.21 |
[Java 고급] 26장 서블릿 및 설정 (0) | 2024.02.19 |
[Java 고급] 25장 UDP 방식의 통신, HTTP 통신 (0) | 2024.02.16 |