JSP - #3 Cookie

임다이·2023년 11월 2일
0

Jsp/Servlet

목록 보기
8/10

  • Cookie & Session
    Client의 정보를 지속적으로 유지하기 위한 방법

    Cookie는 Client PC에 저장이되고, Session은 Server PC에 저장이된다.
    → Cookie가 비용이 더 저렴하다. 쉽게 볼 수 있기 때문에 암호화를 걸어둔다.
  • Cookie
    • 전달할 데이터를 Web Browser(Client)로 보냈다가 Web Server로 되돌려 받는 방법
    • Web페이지 방문 시 브라우저에서의 정보들이 저장된 텍스트 파일
    • 저장위치 : ClientPC
      보안 : 취약
      자원 : Client의 자원을 사용해서 Server에 영향 X
      용량 : 쿠키 1개당 4KB X 300개 = 1.2MB
      저장형식 : 텍스트만 저장 가능, 영어만 가능(한글은 인코딩 필요)

  • Cookie의 특징


  • Cookie 생성 및 동작 과정
  1. Client의 요청(Request)
  2. Cookie를 HTTP Response Header(Set-Cookie)에 담아서 응답
  3. Cookie를 Client의 하드디스크에 저장
  4. Client가 다시 요청(Request)할 때 Cookie를 포함해서 요청
  5. 응답(Cookie 업데이트 시 다시 Cookie 전달)

  • Cookie 객제 생성
  • Cookie 보내기

  • Cookie 조회

실습

  • makeCookie.jsp

    <%@page import="java.net.URLEncoder"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
        <h1> 쿠키 만들기 </h1>
        <ol>
            Cookie : Client의 정보를 유지하기 위해서 사용하는 방법
            <li> 저장위치 : ClientPC </li>
            <li> 보안 : 취약 </li>
            <li> 자원 : Client의 자원을 사용해서 Server에 영향 X </li>
            <li> 용량 : 쿠키 1개당 4KB X 300= 1.2MB </li>
            <li> 저장형식 : 텍스트만 저장 가능, 영어만 가능(한글은 인코딩 필요) </li>
        </ol>
    
        <%
            // 1. 쿠키 객체 생성
            // new Cookie("쿠키이름", "쿠키값")
            // 한글이라면 한글인코딩 -> URLEncoder객체 사용
            Cookie cookie = new Cookie("name", URLEncoder.encode("임다이", "UTF-8"));
    
            // 2. 쿠키의 기한 설정
            // 양수 : 초 단위로 해당 기한만큼 쿠키를 유지
            // 음수 : 브라우저 종료 시 쿠키가 제거
            // 0 : 제거
            cookie.setMaxAge(3600);
    
            // 3. 쿠키 전송
            // 쿠키는 응답할 때 clientPC로 전송 -> response객체 사용
            response.addCookie(cookie);
        %>
    
    </body>
    </html>
  • showCookie.jsp

    <%@page import="java.net.URLDecoder"%>
    <%@page import="java.net.URLEncoder"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
        <h1> 쿠키 조회하기 </h1>
        <%
            // 4. 쿠키 조회하기
            // Server가 따로 요청하지 않아도, request객체에서 조회 가능
            Cookie[] cookies = request.getCookies();
    
            for(int i=0; i<cookies.length; i++){
                out.print("쿠키이름 : " + cookies[i].getName() + "<br>");
                out.print("쿠키값 : " + URLDecoder.decode(cookies[i].getValue(), "UTF-8" ) + "<hr>");
            }
        %>
    
    </body>
    </html>

최근 본 목록 실습

  • List.jsp

    <%@page import="java.net.URLDecoder"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
        <h1> 판매 목록 </h1>
        <ul>
            <li> <a href="./Mouse.jsp"> 마우스 </a> </li>
            <li> <a href="./Computer.jsp"> 컴퓨터 </a> </li>
            <li> <a href="./Phone.jsp"> 핸드폰 </a> </li>
        </ul>
        <hr>
        <h1> 최근 본 상품 </h1>
    
        <%
            // 최근 본 상품 조회
            // 1. 쿠키 조회
            // 2. 쿠키이름에 item이 있다면 웹에 출력
    
            Cookie[] cookies = request.getCookies();
    
            for(int i=0; i<cookies.length; i++){
                if(cookies[i].getName().contains("item")){
                out.print(URLDecoder.decode(cookies[i].getValue(), "UTF-8" ) + "<br>");
                }
            }
    
            /* for(Cookie c : cookies){
                // 만약에 쿠키이름에 item 들어있다면
                // if 쿠키이름.contains("item")
                if(c.getName().contains("item")){
                    // 웹에 출력
                    out.print(URLDecoder.decode(c.getValue(), "UTF-8" ) + "<br>");
                }
            } */
        %>
    
        <hr>
        <a href="./Delete.jsp"> 최근 본 상품 삭제 </a>
    
    </body>
    </html>

  • Mouse.jsp

    <%@page import="java.net.URLEncoder"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
    	<h1> 마우스 상세 페이지 </h1>
    		<h4> 모델명 : 로지텍 마우스 <br>
    		가격 : 100,000</h4>
    		
    		<%
    			Cookie cookie = new Cookie("item1", URLEncoder.encode("마우스", "UTF-8"));
    		
    			response.addCookie(cookie);
    		%>
    	
    	<a href="./List.jsp"> 제품 목록 페이지로 돌아가기 </a>
```
  • Computer.jsp

    <%@page import="java.net.URLEncoder"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
        <h1> 컴퓨터 상세 페이지 </h1>
            <h4> 모델명 : iMac <br>
            가격 : 1,990,000</h4>
    
            <%
                Cookie cookie = new Cookie("item2", URLEncoder.encode("컴퓨터", "UTF-8"));
    
                response.addCookie(cookie);
            %>
    
        <a href="./List.jsp"> 제품 목록 페이지로 돌아가기 </a>
    
    </body>
    </html>

  • Phone.jsp

    <%@page import="java.net.URLEncoder"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
        <h1> 핸드폰 상세 페이지 </h1>
            <h4> 모델명 : 아이폰 15 Pro <br>
            가격 : 1,550,000</h4>
    
            <%
                Cookie cookie = new Cookie("item3", URLEncoder.encode("핸드폰", "UTF-8"));
    
                response.addCookie(cookie);
            %>
    
        <a href="./List.jsp"> 제품 목록 페이지로 돌아가기 </a>
    
    </body>
    </html>

  • Delete.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
        <%
            // 쿠키 삭제 -> 쿠키의 기한을 0으로 설정
            Cookie[] cookies = request.getCookies();
    
            // 쿠키의 이름에 item이 포함된 쿠키만 기한을 0으로 설정
            for(Cookie c : cookies){
                if(c.getName().contains("item")){
                    c.setMaxAge(0);
    
                    // 쿠키가 업데이트 될 때에는 다시 쿠키 보내기
                    response.addCookie(c);
                }
            }
    
            response.sendRedirect("./List.jsp");
    
        %>
    
    </body>
    </html>

profile
노는게 제일 좋아~!

0개의 댓글