JAVA/JSP

[JSP] 세션(Sesstion)

아잠만_ 2024. 7. 16. 16:26

이전 세션 참고하기!

  • 세션과 쿠키는 client와 server 간의 상태를 유지시켜주는 방법
  • 세션과 쿠키는 모두 server에서 생성
  • 세션은 server에 존재하고
  • 쿠키는 client(의 쿠키저장소)에 존재함

세션

세션을 사용하려면 세션을 생성해야 함

  1. 세션 생성  
    JSP 내장 객체인 session.setAttribute(String name, Object value);
    세션의 속성을 설정하면 계속 세션 상태를 유지할 수 있음.
    만약, 동일한 세션의 속성 이름으로 세션을 생성하면 마지막에 설정한 것이 세션 속성 값이 됨
  2. 세션 설명
    1. String name
      세션으로 사용할 세션 속성 이름. 세션에 저장된 특정 값(value)을 찾아오기 위한 키로 사용 됨.
    2. Object value
      세션 속성의 값. Object 객체 타입만 가능하므로 int, double, char 등의 기본 타입은 사용할 수 없음
  3. 세션 메서드
    1. session.setAttribute()
      단일 세션 추가
    2. session.getAttribute()
      단일 세션 정보 얻기
      Object getAttribute(String name)
    3. session.getAttributeNames()
      다중 세션 정보 얻기

      세션에 저장된 여러 개의 세션 속성 이름을 열거형으로 반환
    4. session.removeAttribute();
      지정된 단일 세션 삭제
    5. session.invalidate();
      저장된 전체 세션 삭제
    6. session.getMaxInactiveInterval();
      session.setMaxInactiveInterval(변경초);
      세션 유효시간 가져오기/설정하기
    7. session.getId();
      세션 아이디
    8. session.getCreationTime();
      세션 생성 시간
    9. session.getLastAccessedTime();
      세션 최근에 접근한 시간

JSP Scope 영역

page 영역 request 영역
pageContext 객체 request 객체
동일 JSP 내에서 대이터 공유 동일 요청 내에서 데이터 공유
session 영역 application영역
동일 웹브라우저 내에서 데이터 공유 웹 브라우저 내에서 데이터 공유

세션 추가

session.setAttribute("id", id);
pageContext.setAttribute("id", id);
request.setAttribute("id", id);
application.setAttribute("id", id);
session01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<form action="session01_process.jsp" method="post">
		<p>아이디 : <input type="text" name="id" placeholder="아이디"></p>
		<p>비밀번호 : <input type="password" name="pw" placeholder="비밀번호"></p>
		<p><input type="submit" value="전송"></p>
	</form>
</body>
</html>
session01_process.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<%
	request.setCharacterEncoding("UTF-8");
	String id = request.getParameter("id");
	String pw = request.getParameter("pw");
	
	/*
		세션을 사용하려면 세션을 생성해야 함
		1) 세션 생성  
			JSP 내장 객체인 session.setAttribute(String name, Object value);
			세션의 속성을 설정하면 계속 세션 상태를 유지할 수 있음.
			만약, 동일한 세션의 속성 이름으로 세션을 생성하면 마지막에 설정한 것이 세션 속성 값이 됨
		2) 세션 설명 :
		    String name : 
		    	세션으로 사용할 세션 속성 이름. 세션에 저장된 특정 값(value)
		                  을 찾아오기 위한 키로 사용 됨.
		    Object value : 세션 속성의 값. Object 객체 타입만 가능하므로
		    	int, double, char 등의 기본 타입은 사용할 수 없음
	*/
	if(id.equals("admin")&&pw.equals("java")){
		// sessionScope(아시아) - 동일 웹브라우저 내
		session.setAttribute("id", id);
		session.setAttribute("pw", pw);
		out.print("세션 설정 성공<br>");
		out.print(id+"님 환영합니다");
		
		// pageScope (대전) - 동일 jsp 내
		pageContext.setAttribute("id", id);
		// requestScope (대한민국) - 동일 요청 내
		request.setAttribute("id", id);
		//applicationScope (지구) - 웹브라우저 내
		application.setAttribute("id", id);
	} else {
		out.print("세션 설정 실패");
	}
%>
<h3>입력된 id 값 : <%=id %></h3>
<h3>입력된 pw 값 : <%=pw %></h3>
</body>
</html>
session02.jsp
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script src="/js/jquery.min.js"></script>
<script>
$(function(){
	$('#btnDel').on('click',function(){
		location.href="/ch13/session04.jsp";
	})
	$('#btnAdd').on('click',function(){
		location.href="/ch13/session04_add.jsp";
	})
	$('#btnDelAll').on('click',function(){
		location.href="/ch13/session04_all.jsp";
	})
})
</script>
<title></title>
</head>
<body>
	<%	
	
		// 생성된 세션의 정보를 가져오기
		/*
		1. getAttribute() : 단일 세션 정보 얻기
			Object getAttribute(String name)
		2. getAttributeNames() : 다중 세션 정보 얻기
		*/
		// Object 타입
		String id = (String) session.getAttribute("id"); // admin;
		String pw = (String) session.getAttribute("pw"); // java;
		String id2 = (String) pageContext.getAttribute("id"); // admin;
		String id3 = (String) request.getAttribute("id"); // admin;
		String id4 = (String) application.getAttribute("id"); // admin;
	%>
	<p>설정된 세션 속성 값 : <%=id %></p>
	<p>설정된 세션 속성 값 : <%=pw %></p>
	<p>설정된 pageContext 속성 값 : <%=id2 %></p>
	<p>설정된 request 속성 값 : <%=id3 %></p>
	<p>설정된 application 속성 값 : <%=id4 %></p>
	<hr>
	<% 
		String name = "";
		String value = "";
		// 세션에 저장된 모든 세션 속성 이름을 리턴
		Enumeration names = session.getAttributeNames();
		int i= 0;
		// 세션 속성 이름이 있을 때까지만 반복
		while(names.hasMoreElements()){
			name = names.nextElement().toString();
			value = session.getAttribute(name).toString();
			 out.print("설정된 세션 속성 명 [" + i + "] : " + name + "<br />");
	         out.print("설정된 세션 속성 값 [" + i + "] : " + value + "<br />");
	         out.print("<hr />");
	         i++;
		}
	%>
	<button type="button" id="btnDel">id 세션 삭제</button>
	<button type="button" id="btnAdd">id 세션 추가</button>
	<button type="button" id="btnDelAll">모든 세션 속성 이름 삭제</button>
</body>
</html>
session04_add.jsp
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>id라는 session객체의 속성명</title>
</head>
<body>
	<%	
	// 세션에 저장된 이름 id 추가
		session.setAttribute("id","admin");
	
	// 결과 확인
		response.sendRedirect("/ch13/session02.jsp");
	%>
</body>
</html>

세션 삭제

session.removeAttribute("이름");
session04.jsp
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>id라는 session객체의 속성명</title>
</head>
<body>
	<%	
	// 세션에 저장된 이름 id 삭제
		session.removeAttribute("id");
	
	// 결과 확인
		response.sendRedirect("/ch13/session02.jsp");
	%>
</body>
</html>

세션 전부 삭제 

session.invalidate();
(application은 삭제되지 않음)
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>id라는 session객체의 속성명</title>
</head>
<body>
	<%	
	// 다중 세션 삭제
	// session.invalidate();
	// 세션에 저장된 모든 세션 속성 이름 삭제
    // application을 제외한 모든 세션 삭제
		session.invalidate();
        
	// application은 전체 삭제 없음
		application.removeAttribute("id");
        
	// 결과 확인
		response.sendRedirect("/ch13/session02.jsp");
	%>
</body>
</html>

세션 유효시간 변경

session.getMaxInactiveInterval();
session.setMaxInactiveInterval(변경초);
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>session</title>
</head>
<body>
	<h4>----------세션 유효시간 변경 전 --------</h4>
	<%
	/*
	    세션 유효 시간 : 세션을 유지하기 위한 세션의 일정 시간
	       웹 브라우저(크롬)에 마지막 접근한 시간부터 일정 시간 이내에 다시 웹 브라우저에
	          접근하지 않으면 자동으로 세션이 종료됨
	    세션 유효 시간 설정 : void setMaxInactiveInterval(int interval) : 초단위
    */
    
		// 세션에 설정된 유효 시간(기본 1800초 (30분))
		int time = session.getMaxInactiveInterval(); // 초단위
	%>
	<p>세션 유효 시간 : <%=time %></p>
	<h4>----------세션 유효시간 변경 후 --------</h4>
	<%
		session.setMaxInactiveInterval(60*60); // 초단위
		
		time = session.getMaxInactiveInterval(); // 초단위
	%>
	<p>세션 유효 시간 : <%=time %></p>
	
</body>
</html>

머문 시간

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>session</title>
</head>
<body>
	<%
		//java.util.Date
	    Date time = new Date();
	    //간단날짜형식. java.text.SimpleDateFormat
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
		// 고유한 세션 내장 객체의 아이디
		String sessionId = session.getId();
	
		// 세션이 생성된 시간
		//1970년 1월 1일 이후 흘러간 시간을 의미, 단위는 ms
		long startTime = session.getCreationTime();
		
		// 세션에 마지막으로 접근한 시간
		long lastTime = session.getLastAccessedTime();
		
		// 웹 사이트에 머문 시간
		long userTime = lastTime - startTime;
	%>
	<p>세션 아이디 : <%=sessionId %></p>
	<p>요청시작 시간 : <%=format.format(startTime) %></p>
	<p>요청 마지막 시간 : <%=format.format(lastTime) %></p>
	<p>웹 사이트의 경과시간 : <%=userTime/(1000*60)%>분</p>
</body>
</html>