JSP
[JSP] session
NamGH
2023. 9. 25. 17:32
session : JSP 페이지를 요청한 웹 브라우저의 정보를 저장하기 위한 객체
웹 브라우저 당 1개만 할당
회원 관리 시스템에서 사용자 인증에 관련된 작업을 수행할 때 사용
- 요청한 웹 브라우저에 대한 정보를 저장하고 관리하는 내장 객체
- 웹 브라우저(클라이언트)당 1개가 할당
- 주로 회원관리에서 사용자 인증에 관련된 작업을 수행할 때 사용
- page 디렉티브의 [session = true]인 경우에만 session 객체를 별도로 생성하지 않고 암묵적으로 사용할 수 있다
- •session.setAttribute(key, value) – session.setAttribute("id", id) : id 속성에 id값으로 설정
- session.getAttribute(키) – session.getAttribute("id") : id 속성으로 설정한 값 가져오기
- session.setMaxInactiveInterval(60*2) – 해당 세션을 유지할 시간을 초단위로 설정(디폴트 세션 타임은 30분)
- session.invalidate() : 세션 무효화
예제
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<form method="post" action = "session1.jsp">
아이디 : <input type = "text" name="id"><br>
패스워드 : <input type = "password" name="password">
<input type = "submit" value = "로그인">
</form>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
%>
<%
String id = request.getParameter("id");
String pw = request.getParameter("password");
out.println("아이디: " + id + "<br>");
out.println("패스워드: " + pw + "<br>");
%>
<%
session.setAttribute("id", id); //속성,값 >> 속성에 값을 넣음
session.setAttribute("password", pw);
session.setMaxInactiveInterval(10); //10초 지나면 설정한 세션해제
%>
<form method = "post" action="session2.jsp">
☆가장 좋아하는 스포츠를 선택하세요☆ <br>
<input type="radio" name = "sports" value="태권도">태권도
<input type="radio" name = "sports" value="유도">유도
<input type="radio" name = "sports" value="이종격투기">이종격투기
<input type="radio" name = "sports" value="레슬링">레슬링<br><br>
☆가장 좋아하는 게임을 선택하세요☆ <br>
<select name = "game">
<option value="카트라이더">카트라이더</option>
<option value="리니지">리니지</option>
<option value="로스트아크">로스트아크</option>
<option value="메이플스토리">메이플스토리</option>
</select><br><br>
<input type = "submit" value="전송">
</form>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
%>
<%
String id = request.getParameter("id");
String id2 = (String)session.getAttribute("id");
String pw = request.getParameter("password");
String pw2 = (String)session.getAttribute("password");
String sports = request.getParameter("sports");
String game = request.getParameter("game");
%>
<%
if(id2 != null){
out.println("아이디: " + id + "<br>");
out.println("아이디2: " + id2 + "<br>");
out.println("패스워드: " + pw + "<br>");
out.println("패스워드2: " + pw2 + "<br>");
out.println("스포츠: " + sports + "<br>");
out.println("게임: " + game + "<br>");
session.invalidate();
} else{
out.println("세션 설정하지 않음");
}
%>
실행결과
코드설명
세션을 사용하지 않고 세션1을 거쳐서 세션2로 바로가면 아이디값과 패스워드 값은 null값이다
하지만 세션을 사용해서 넘기면 객체를 공유하기 때문에 아이디와 패스워드 값이 뜨게 된다
session.invalidate();의 경우 세션설정을 무효화하여 뒤로가기를 누르고 다시 전송을 누르게 되면 모든 값이 안뜨게 비활성화 하는 것이다
session.setMaxInactiveInterval(10);같은 경우 10초를 설정하여 10초가 지날시 세션을 해제 시키는 것이다
session.setAttribute("id", id);은 속성과 값인데 속성에 값인"id"에 넣는다는것을 의미한