Java EE 정리 05
04 Mar 2019
Reading time ~5 minutes
Java EE 정리 05 - Session, Cookie
Session
-
접속자의 정보를 서버측 메모리에 저장한다.
- 접속자의 Web Browser타입마다 ID를 저장
- 모든 브라우저에 적용할 수 있다.
-
모든 데이터형이 저장될 수 있다.
- 클라이언트가 서버로 전달하는 데이터는 모두 String
- 서버측에서 다루는 데이터는 모든 형태가 가능
- HttpSession 인터페이스 사용
- Tomcat 실행 시 자동으로 세션 객체 생성
- 그 공간을 가져다 쓰는 것, Container 성능에 의존적
// 1. HttpSession 얻기
// Container에는 정보를 저장하기 위한 Session이 생성되어 있다.
HttpSession session = request.getSession();
// 2. 생존시간 설정 (Tomcat Session은 기본 시간 30분)
// 사용자가 동작을 멈춘 상태에서 다음 동작이 일어나는 사이 시간 설정(interval)
session.setMaxInactiveInterval(초); // (초*분*시*일)입력, 직접 계산안해도 된다!
// 한번 변경된 시간은 계속 유지된다.
// 3. 값 설정
session.setAttribute("이름", 값); // (String, Object)
// 4. 값 얻기
session.getAttribute("이름"); // 사용할땐 casting 필수!
// 5. 값 삭제
session.removeAttribute("이름");
// 6. 세션을 무효화
session.invalidate();
- 세션은 컨테이너가 실행되면서 자동으로 생성
- 요청이 들어오면 세션에 사용할 브라우저 ID를 생성하고 처음 응답할 때 같이 전달
- 이 브라우저 ID를 이용, 브라우저 별 Session 정보를 저장
- Map 속에 Map 형태
- 접속자가 연결을 끊고 일정시간이 지나면 세션을 삭제된다.
- 세션 사용 예
<!-- use_session.html -->
<script type="text/javascript">
$(document).ready(function() {
$(".btn").click(function() {
checkNull();
});
$("[name='id']").keydown(function(evt) {
if(evt.which == 13) {
checkNull();
}
});
});
function checkNull() {
var id = $("[name='id']").val();
var pass = $("[name='pass']").val();
if(id == "") {
$("[name='id']").focus();
return;
}
if(pass == "") {
$("[name='pass']").focus();
return;
}
$("form").submit();
}
</script>
...
<div>
<form method="post" action="../use_session_a">
<table>
<tr>
<td colspan="2" align="center">
세션사용 로그인
</td>
</tr>
<tr>
<td>
<input type="text" name="id" placeholder="아이디" autofocus="autofocus" class="inputBox"/>
</td>
<td rowspan="2">
<input type="button" value="로그인" class="btn" style="height:45px; width:80px;">
</td>
</tr>
<tr>
<td>
<input type="password" name="pass" placeholder="비밀번호" class="inputBox"/>
</td>
</tr>
</table>
</form>
</div>
// UseSessionA.java
@SuppressWarnings("serial")
public class UseSessionA extends HttpServlet {
private Map<String, String> loginMap;
public void init() {
loginMap = new HashMap<String, String>();
loginMap.put("kim", "김정윤");
loginMap.put("lee", "이재찬");
loginMap.put("park", "박영민");
loginMap.put("roh", "노진경");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 응답 방식을 설정
response.setContentType("text/html;charset=UTF-8");
// 출력스트림 얻기
PrintWriter out = response.getWriter();
...
// 접속자가 입력한 parameter 받기
String id = request.getParameter("id");
String pass = request.getParameter("pass");
if(loginMap.containsKey(id) && "123".equals(pass)) {
// 로그인 성공
String name = loginMap.get(id);
// 로그인 정보를 세션에 추가
// 1. 세션 얻기
HttpSession session = request.getSession();
// 2. 세션 생존시간 설정(Tomcat 기본은 30분)
session.setMaxInactiveInterval(60*2);
// 3. 세션에 값 설정
session.setAttribute("id", id);
session.setAttribute("user_name", name);
out.println("<h2>세션사용 로그인</h2>");
out.print("<strong>");
out.print(id);
out.print("</strong>(");
out.print(name);
out.println(")님 로그인 하셨습니다.<br/>");
out.println("<a href='use_session_b'>작업페이지로 이동</a>");
} else {
out.println("<strong>아이디나 비밀번호를 확인해주세요.</strong><br/>");
out.println("다시 <a href='date0304/use_session.html'>로그인</a>");
}
...
}
}
// UseSessionB.java
@SuppressWarnings("serial")
public class UseSessionB extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
...
// 다른 페이지(UseSessionA)에서 사용한 값을 이동한 페이지(UseSessionB)에서
// 사용할려면 session이 필요(비연결성의 관계 유지)
// 1. 세션 얻기
HttpSession session = request.getSession();
// 2. 값 얻기
String id = (String)session.getAttribute("id");
String name = (String)session.getAttribute("user_name");
if (id == null) { // 세션이 없을 때 예외처리
// 세션에 값이 없다면
// 이 페이지의 url을 직접 넣고 들어왔는가? - 비정상적인 요청
// 정상적인 요청을 했지만 세션의 사용시간(interval)을 초과한 경우
response.sendRedirect("date0304/use_session.html");
return;
}
// 3. 값 사용
out.println("<h2>세션사용</h2>");
out.print(name);
out.print("(<strong>");
out.print(id);
out.println("</strong>)님의 작업 페이지입니다.<br/>");
out.println("<a href='use_session_c'>로그아웃</a><br/>");
out.println("<img src='http://localhost:8080/servlet_prj/date0304/images/job.png'>");
...
//UseSessionC.java
@SuppressWarnings("serial")
public class UseSessionC extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// 세션 삭제 페이지
// 1. 세션 얻기
HttpSession session = request.getSession();
// 2. 세션 값 삭제
session.removeAttribute("id");
session.removeAttribute("user_name");
// 3. 브라우저에 할당된 세션자체 무효화
session.invalidate();
// String id = (String)session.getAttribute("id");
// String name = (String)session.getAttribute("user_name");
// 세션이 무효화 된 이후에는 세션에서 값을 얻을 수 없다.
// 4. 이동할 페이지 설정
response.sendRedirect("date0304/use_session.html");
}
}
-
히스토리가 존재하기 때문에 로그아웃 이후에도 뒤로가기 가능
- 세션이 살아있다!..
- 페이지 이동을 location.replace로 수행해야 뒤로가기를 막을 수 있음
// UseSessionA.java
...
out.println("<script type='text/javascript'>");
out.println("window.onload = function() {");
out.println("\tdocument.getElementById('job').addEventListener('click',movePage);");
out.println("}");
out.println("function movePage() {");
out.println("\tlocation.replace('use_session_b');");
out.println("}");
out.println("</script>");
...
...
out.println("<a id='job'>작업페이지로 이동</a>");
...
// UseSessionB.java
...
out.println("<script type='text/javascript'>");
out.println("window.onload = function() {");
out.println("\tdocument.getElementById('logout').addEventListener('click',movePage);");
out.println("}");
out.println("function movePage() {");
out.println("\tlocation.replace('use_session_c');");
out.println("}");
out.println("</script>");
...
out.println("<a id='logout'>로그아웃</a><br/>");
...
// UseSessionC.java
...
out.println("<script type='text/javascript'>");
out.println("window.onload = function() {");
out.println("\tlocation.replace('date0304/use_session.html');");
out.println("}");
out.println("</script>");
...
Cookie
-
접속자의 정보를 접속자 컴퓨터에 File로 저장
- String만 저장가능
- 한글은 쿠키로 심어지지 않는다.
- 중요정보를 저장하지 않는다.
- 쿠키를 지원하지 않는 브라우저에서는 사용할 수 없다.
- 요즘은 Cookie보다 HTML Storage를 쓰는 추세(권장)
// 1. 객체화
Cookie c = new Cookie("이름", "값");
// 2. 쿠기의 생존시간 설정
c.setMaxAge(초)
// 2. 쿠키 심기, 심어진 쿠키는 생존시간만큼 유지
// HttpServletResponse 객체를 이용
response.addCookie(c);
// 4. 쿠기 읽기, 다른 서버에서 심은 쿠키는 읽어들일 수 없다.
// HttpServletRequest 객체를 이용
Cookie[] cookies = request.getCookies();
for(int i=0; i<cookies.length; i++) {
Cookie c = cookies[i];
String cName = c.getName(); // 쿠키의 이름 얻기
String cValue = c.getValue(); // 쿠키의 값 얻기
}
// 5. 쿠키삭제
// 5-1. 지우려는 이름과 같은 이름을 가진 쿠키를 생성
Cookie c = new Cookie("이름","");
// 5-2. 생존시간을 0으로 설정
c.setMaxAge(0);
// 5-3. 쿠키 심기
response.addCookie(c);
-
쿠키 사용 예
- 쿠기 심기->사용->삭제
// GetCookie.java
@SuppressWarnings("serial")
public class GetCookie extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
...
// 접속자에게 심어진 쿠키 읽기
Cookie[] cookies = request.getCookies();
if (cookies != null) {
// Cookie가 있을 때
Cookie temp = null;
out.println("<ul>");
for(int i=0; i<cookies.length; i++) {
temp = cookies[i];
out.print("<li>쿠키 이름 : <strong>");
out.print(temp.getName());
out.print("</strong> 쿠키 값 : ");
out.print(temp.getValue());
out.print("</li>");
}
out.println("</ul>");
out.println("<div><a href='add_cookie'>쿠키 심기</a></div>");
out.println("<div><a href='remove_cookie'>쿠키 삭제</a></div>");
} else {
// Cookie가 없을 때
out.println("<div id='non_cookie'>쿠키가 존재하지 않습니다.</div>");
out.println("<div><a href=''>쿠키 심기</a></div>");
}
...
// AddCookie.java
@SuppressWarnings("serial")
public class AddCookie extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
...
// 쿠키 심기
// 1. 쿠키 생성
Cookie nameCookie = new Cookie("name", "young");
Cookie ageCookie = new Cookie("age", "30");
// 2. 생존 시간 설정 : 생존시간을 설정하지 않으면 브라우저가 떠있는 동안에만 유지됨
nameCookie.setMaxAge(60*60*24*1);
// 3. 쿠키심기
response.addCookie(nameCookie);
response.addCookie(ageCookie);
out.println("쿠키 심기 완료<br/>");
out.println("<a href='get_cookie'>쿠키 읽기</a>");
...
// RemoveCookie.java
@SuppressWarnings("serial")
public class RemoveCookie extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
...
// 쿠키 삭제
// 1. 삭제할 쿠키가 가진 같은 이름의 쿠키 생성
Cookie co = new Cookie("name", "");
// 2. 생존시간 설정
co.setMaxAge(0);
// 3. 쿠키 심기
response.addCookie(co);
out.println("쿠키 삭제 완료<br/>");
out.println("<a href='get_cookie'>쿠키 읽기</a>");
...