세션
- 클라이언트와 웹 서버 간의 상태를 지속적으로 유지하는 방법
- 로그인 인증을 통해 사용권한 부여
- 다른 웹 페이지에 갔다가 되돌아와도 로그인 상태가 유지
- 세션은 웹 서버에서만 접근 가능
- invalidate() 메소드 중요 : 현재 세션에 저장된 모든 세션 속성을 제거
세션 생성
- session 내장 객체의 setAttrubute() 메소드를 사용
- setAttrubute() 메소드를 이용하여 세션의 속성을 설정하면 계속 세션 상태를 유지할 수 있음
ex)
<%@ page contentType="text/html; charset=utf-8"%>
<html>
<head>
<title>Session</title>
</head>
<body>
<form action="session01_process.jsp" method="POST">
<p> 아 이 디 : <input type="text" name="id">
<p> 비밀번호 : <input type="text" name="passwd">
<p> <input type="submit" value="전송">
</form>
</body>
</html>
session01_process.jsp
<%@ page contentType="text/html; charset=utf-8"%>
<html>
<head>
<title>Session</title>
</head>
<body>
<%
String user_id = request.getParameter("id");
String user_pw = request.getParameter("passwd");
if (user_id.equals("admin") && user_pw.equals("1234")) {
session.setAttribute("userID", user_id);//setAttribute() 메소드로 아이디와 비밀번호를 기록
session.setAttribute("userPW", user_pw);
out.println("세션 설정이 성공했습니다<br>");
out.println(user_id+"님 환영합니다");
} else {
out.println("세션 설정이 실패했습니다");
}
%>
</body>
</html>
단일 세션 정보 얻기
- 세션에 저장된 하나의 세션 속성 이름에 대한 속성 값을 얻어오려면 getAttribute() 메소드를 사용
- 반환 유형이 Object형이므로 반드시 형 변환 필요
ex)
<%@ page contentType="text/html; charset=utf-8"%>
<html>
<head>
<title>Session</title>
</head>
<body>
<%
String user_id = (String) session.getAttribute("userID"); //String으로 형변환 세션 정보 가지고옴
String user_pw = (String) session.getAttribute("userPW");
out.println("설정된 세션의 속성 값 [1] : " + user_id + "<br>");
out.println("설정된 세션의 속성 값 [2] : " + user_pw);
%>
</body>
</html>
다중 세션 정보 얻기
- getArributeNames() 메소드 사용
ex)
<%@ page contentType="text/html; charset=utf-8"%>
<%@ page import="java.util.Enumeration"%>
<html>
<head>
<title>Session</title>
</head>
<body>
<%
String name;
String value;
Enumeration en = session.getAttributeNames(); //세션 모든 정보를 저장
int i = 0;
while (en.hasMoreElements()) {//요소가 없을 때까지 반복
i++;
name = en.nextElement().toString(); //en의 다음요소 저장
value = session.getAttribute(name).toString();
out.println("설정된 세션의 속성 이름 [ " + i + " ] : " + name + "<br>");
out.println("설정된 세션의 속성 값 [ " + i + " ] : " + value + "<br>");
}
%>
</body>
</html>
세션 삭제
- 하나의 세션 속성 이름을 삭제하려면 removeArrtibute() 메소드 사용
- 세션은 30분 지나면 없어짐
ex)
<%@ page contentType="text/html; charset=utf-8"%>
<html>
<head>
<title>Session</title>
</head>
<body>
<p><h4>----- 세션을 삭제하기 전 -----</h4>
<%
String user_id = (String) session.getAttribute("userID"); // 세션 정보를 얻음
String user_pw = (String) session.getAttribute("userPW");
out.println("설정된 세션 이름 userID : " + user_id + "<br>");
out.println("설정된 세션 값 userPW : " + user_pw + "<br>");
session.removeAttribute("userID"); //세션 속성이름 userID를 삭제
%>
<p><h4>----- 세션을 삭제한 후 -----</h4>
<%
user_id = (String) session.getAttribute("userID");
user_pw = (String) session.getAttribute("userPW");
out.println("설정된 세션 이름 userID : " + user_id + "<br>");
out.println("설정된 세션 값 userPW : " + user_pw + "<br>");
%>
</body>
</html>
다중 세션 삭제
- 세션에 저장된 모든 세션 속성 이름을 삭제하려면 invalidate() 메소드를 사용
ex)
<%@ page contentType="text/html; charset=utf-8"%>
<html>
<head>
<title>Session</title>
</head>
<body>
<p> <h4>----- 세션을 삭제하기 전 -----</h4>
<%
String user_id = (String) session.getAttribute("userID");
String user_pw = (String) session.getAttribute("userPW");
out.println("설정된 세션 이름 userID : " + user_id + "<br>");
out.println("설정된 세션 값 userPW : " + user_pw + "<br>");
if (request.isRequestedSessionIdValid() == true) {
out.print("세션이 유효합니다.");
}else {
out.print("세션이 유효하지 않습니다.");
}
session.invalidate();// 저장된 모든 세션 속성을 삭제
%>
<p> <h4>----- 세션을 삭제한 후 -----</h4>
<%
if (request.isRequestedSessionIdValid() == true) {
out.print("세션이 유효합니다.");
}else {
out.print("세션이 유효하지 않습니다.");
}
%>
</body>
</html>
세션 유효 시간 설정
- 세션 유효 시간을 설정하기 위해 session 내장객체 setMaxInactiveInterval() 메소드 사용
- 세션 유효 시간을 0이나 음수로 설정하면 세션 유효 시간이 없는 상태
- 세션 유효 시간이 없는 상태에서 session.invalidate() 메소드를 명시적으로 실행하지 않으면 세션이 계속 메모리에 남아있어 시간이 흐르면 메모리 부족현상 발생
ex)
<%@ page contentType="text/html; charset=utf-8"%>
<html>
<head>
<title>Session</title>
</head>
<body>
<p> <h4>----- 세션 유효 시간 변경 전 -----</h4>
<%
int time = session.getMaxInactiveInterval() / 60;
out.println("세션 유효 시간 : " + time + "분<br>");
%>
<p> <h4>----- 세션 유효 시간 변경 후 -----</h4>
<%
session.setMaxInactiveInterval(60 * 60);//세션 유효시간 6분으로 설정
time = session.getMaxInactiveInterval() / 60;
out.println("세션 유효 시간 : " + time + "분<br>");
%>
</body>
</html>
쉽게 배우는 JSP 웹 프로그래밍
송미영 지음 한빛 아카데미