티스토리 뷰

JSP

[JSP] 쿠키(Cooki), 세션(Session)

먹태 2018. 7. 11. 15:52

1. 쿠키


웹브라우저에서 서버로 어떤 데이터를 요청하면 서버측에서는 

알맞은 로직을 수행 -> 데이터를 웹브라우저에 응답 -> 서버는 웹브라우저를 종료 

이렇게 웹브라우저에 응답 후 관계를 끊는 것은 http프로토콜의 특징이다.


- 쿠키는 연결이 끊겼을 때, 어떤 정보를 지속적으로 유지하기 위한 수단으로 사용한다.

- 쿠키는 서버에서 생성하여 서버가 아닌 클라이언트측에 특정 정보를 저장한다(데이터를 웹브라우저에 저장한다)

- 그리고 서버에 요청할 때 마다 쿠키의 속성값을 참조 또는 변경할 수 있다

- 용량이 제한적이고 300개 까지 데이터 정보를 가질 수 있다

  (보안상 문제때문에 사용빈도가 많이 줄어들었지만 그래도 알고있어야 하는 개념)

- 쿠키생성 -> 속성설정 -> response객체에 탑승






<쿠키사용 간단한 로그인 예제>

-DB사용 ㄴㄴ, 특정 ID 하나만 로그인 했을때



<login.html>

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8. <form action="loginOk.jsp">
  9.     ID : <input type = "text" name="id">
  10.     PW : <input type = "text" name="pw">
  11.     <input type="submit" value="로그인">
  12. </form>
  13. </body>
  14. </html>






<loginOk.jsp>

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2.     pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10.     <%!
  11.         String id,pw;
  12.     %>
  13.    
  14.     <%
  15.         id = request.getParameter("id");
  16.         pw = request.getParameter("pw");
  17.        
  18.         if(id.equals("asdf") && pw.equals("1234")){
  19.             Cookie cookie = new Cookie("id", id)//쿠키객체 생성, 앞에id값에다가 내가 만든 id값 삽입
  20.             cookie.setMaxAge(60)//쿠키유지 최대시간 설정, 60초
  21.             response.addCookie(cookie)//response객체에 탑재
  22.             response.sendRedirect("welcome.jsp")//로그인 성공시 페이지 이동
  23.         } else {
  24.             response.sendRedirect("login.html")//실패시 다시 로그인창
  25.         }
  26.     %>
  27. </body>
  28. </html>




<welcome.jsp>

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2.     pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10.  
  11.     <%
  12.         Cookie[] cookies = request.getCookies();
  13.        
  14.         for(int i=0; i < cookies.length; i++){
  15.             String id = cookies[i].getValue();
  16.             if(id.equals("asdf")){
  17.                 out.print(id + "님 환영합니다");
  18.             }
  19.         }
  20.     %>
  21.  
  22. </body>
  23. </html>









2. 세션 (Session)


- 세션도 쿠키와 마찬가지로 서버와의 관계를 유지하기 위한 수단이다

  단, 쿠키와 달리 클라이언트의 특정 위치에 저장되는것이 아니라, 서버상에 객체로 존재한다.

  따라서 세션은 서버에서만 접근이 가능하여 보안이 좋고 저장할 수 있는 데이터에 한계가 없다.

- 서버 컨테이너에서 클라이언트의 요청이 발생하면 자동으로 생성

- 클라이언트 요청 -> 세션 자동생성 -> 세션속성설정(내부객채사용)




<login.jsp>

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8. <form action="loginOk.jsp">
  9.     ID : <input type = "text" name="id">
  10.     PW : <input type = "password" name="pw">
  11.     <input type="submit" value="로그인">
  12. </form>
  13.  
  14. </body>
  15. </html>




<loginOk.jsp>


  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2.     pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10.     <%!
  11.         String id,pw;
  12.     %>
  13.    
  14.     <%
  15.         id = request.getParameter("id");
  16.         pw = request.getParameter("pw");
  17.        
  18.         if(id.equals("asdf") && pw.equals("1234")){
  19.             session.setAttribute("id", id);
  20.             response.sendRedirect("welcome.jsp")//로그인 성공시 페이지 이동
  21.         } else {
  22.             response.sendRedirect("login.html")//실패시 다시 로그인창
  23.         }
  24.     %>
  25.  
  26.  
  27. </body>
  28. </html>





<welcome.jsp>

  1. <%@page import="java.util.Enumeration"%>
  2. <%@ page language="java" contentType="text/html; charset=UTF-8"
  3.     pageEncoding="UTF-8"%>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  8. <title>Insert title here</title>
  9. </head>
  10. <body>
  11.  
  12.     <%
  13.         Enumeration enumeration = session.getAttributeNames();
  14.         while(enumeration.hasMoreElements()){
  15.             String sName = enumeration.nextElement().toString();
  16.             String sValue = (String)session.getAttribute(sName);
  17.        
  18.         if(sValue.equals("asdf")){
  19.             out.print(sValue + "님 환영합니다.");
  20.         }
  21.     }  
  22.     %>
  23.     <br>
  24.     <a href="logout.jsp">로그아웃</a>
  25. </body>
  26. </html>

- Enumeration을 처음봐서 찾아보니까 순서가 있는 배열의 종류라고 생각하면 될거같다.




<logout.jsp>

- removeAttriute로 세션삭제


  1. <%@page import="java.util.Enumeration"%>
  2. <%@page import="com.sun.jmx.snmp.Enumerated"%>
  3. <%@ page language="java" contentType="text/html; charset=UTF-8"
  4.     pageEncoding="UTF-8"%>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  9. <title>Insert title here</title>
  10. </head>
  11. <body>
  12.     <%
  13.         Enumeration enumeration = session.getAttributeNames();
  14.         while (enumeration.hasMoreElements()){
  15.             String sName = enumeration.nextElement().toString();
  16.             String sValue = (String)session.getAttribute(sName);
  17.        
  18.             if(sValue.equals("asdf")){
  19.                     session.removeAttribute(sName);
  20.                 }
  21.             }
  22.     %>
  23.  
  24.     <a href="sessionTest.jsp">session TEST</a>
  25.  
  26. </body>
  27. </html>





<sessionTest.jsp>

- 세션이 삭제됐는지 확인



  1. <%@page import="java.util.Enumeration"%>
  2. <%@ page language="java" contentType="text/html; charset=UTF-8"
  3.     pageEncoding="UTF-8"%>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  8. <title>Insert title here</title>
  9. </head>
  10. <body>
  11.     <%
  12.         Enumeration enumeration = session.getAttributeNames();
  13.         int i = 0;
  14.         while(enumeration.hasMoreElements()){
  15.             i++;
  16.             String sName = enumeration.nextElement().toString();
  17.             String sValue = (String)session.getAttribute(sName);
  18.            
  19.             out.println("sName : "  + sName + "<br>");
  20.             out.println("sValue : "  + sValue + "<br>");
  21.         }
  22.        
  23.         if(i==0){
  24.             out.println("세션이 모두 삭제되었습니다.");
  25.         }
  26.     %>
  27. </body>
  28. </html>


댓글
최근에 올라온 글
최근에 달린 댓글
링크
Total
Today
Yesterday