Server

JSP STEP 5 - Session

IT의 큰손 2023. 5. 9. 17:06
728x90

★ Session

  • 세션에 저장한 변수  : 전역 변수(페이지간에 전달 과정 없이 언제든 입출력 가능)
  • 세션에 저장한 변수 : 접속 종료전까지 계속 유지가 된다.(상태 유지 도구 역할)
  • 세션 객체의 활용 용도 > 상태 유지를 가능하게 한다.
//선언
<% session.setAttribute("d", 40); %>
//실행
<div> d: <%= session.getAttribute("d") %></div>
  • 방문자 Count Session
  • 이 세션은 브라우저 종류에 따라, 사람에 따라 다른 사람으로 인식하여, 카운트가 다르게 셋팅됨.
if(session.getAttribute("count")==null) {
    session.setAttribute("count", 1);
}else {
    session.setAttribute("count", (int)session.getAttribute("count") + 1);
}
  • 출력 구문
<h1>세션</h1>

<div>방문 카운트 : <%= session.getAttribute("count") %></div>
  • 실행 결과

실행 결과

 

■ 세션 정보 확인

<h2>세션 정보 확인</h2>
<div>Session ID : <%= session.getId() %></div>
<div>Session Creation Time : <%= session.getCreationTime() %></div>
<div>Session Max Inactive Interval : <%= session.getMaxInactiveInterval() %></div>
<div>Session isNew : <%= session.isNew() %></div>
  • 실행 결과

세션 정보

  • Tick값을 Calendar로 변환
<%

	long tick = session.getCreationTime();
	Calendar time = Calendar.getInstance();
	time.setTimeInMillis(tick); //tick > Calendar

%>
<div>Session Creation Time : <%= String.format("%tF %tT", time, time) %></div>
  • 실행 결과

tick값으로 나온 Creation Time을 Calendar를 통해 변환

 

 

■ 세션 조작

  • set : 세션값 저장하기 -> ex16_set.jsp
<a href="ex16_set.jsp">세션값 저장하기</a>
<h1>세션값 저장하기</h1>

<%

    session.setAttribute("data", "홍길동");

%>

<a href="ex16_session.jsp">돌아가기</a>
  • del : 세션값 삭제하기 -> ex16_del.jsp
<a href="ex16_del.jsp">세션값 삭제하기</a>
<h1>세션값 삭제하기</h1>

<%

    session.removeAttribute("data");

%>

<a href="ex16_session.jsp">돌아가기</a>
  • reset : 세션 초기화 -> ex16_reset.jsp
<a href="ex16_reset.jsp">세션 초기화</a>
<h1>세션 초기화</h1>

<%

    //세션을 새것으로 교체
    session.invalidate();

%>

<a href="ex16_session.jsp">돌아가기</a>
  • interval : 세션 만료 시간 지정 -> ex16_interval.jsp
  • 자주 사용 안함 -> because > risk가 너무 큼..
<a href="ex16_interval.jsp">세션 만료 시간 지정</a>
<h1>세션 만료 시간 지정</h1>

<%

    //1800
    session.setMaxInactiveInterval(30);

%>

<a href="ex16_session.jsp">돌아가기</a>

 

728x90