ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [jsp] 쿠키생성, 쿠키 정보 얻기, 쿠키 삭제
    jsp 2023. 5. 24. 15:05

    쿠키?

    세션과 마찬가지로 웹 서버 간의 상태를 지속적으로 유지하는 방법이다. 쿠키는 세션과 달리 상태 정보를 웹 서버가 아닌 클라이언트에 저장한다. 이를 통해 웹 서버 부하를 줄일 수 있다는 장점이 있으나, 웹 사이트 관한 정보와 개인 정보가 클라이언트에 기록되기 때문에 보안상 문제가 있다.

     

    쿠키 동작 과정

    쿠키 생성 단계 : 웹 서버 측에서 생성한다. 생성된 쿠키는 response객체에 함께 저장되어 웹 브라우저에 전송된다.

    쿠키 저장 단계 : 웹 브라우저는 응답 데이터에 포함된 쿠키를 쿠키 저장소에 보관한다. 메모리나 파일로 저장된다.

    쿠키 전송 단계 : 웹 브라우저는 한 번 저장된 쿠키를 서버에 접속할 때마다 request 객체를 통해 웹 서버에 전송한다. 웹 서버는 웹 브라우저가 전송한 쿠키를 사용하여 필요한 작업을 수행한다. 

     

    • 일단 웹 브라우저에 쿠키가 저장되면 웹 브라우저는 쿠키가 삭제되기 전까지 웹 서버에 쿠키를 전송한다.
    • 따라서 웹 애플리케이션을 사용하는 동안 지속적으로 유지해야 하는 정보는 쿠키를 이용해서 저장하면 된다.

     

    쿠키 클래스의 메소드 종류

    jsp에서, 쿠키와 세션의 차이

     

    1. 쿠키 생성

    1. Cookie() 생성자를 이용해 쿠키를 생성한다.

    Cookie cookie = new Cookie("쿠키 식별하기 위한 이름","쿠키 값")

    2. 쿠키를 생성한 후에는 반드시 response 내장 객체의 addCookie()메소드를 사용하여 쿠키를 웹 브라우저(클라이언트)에게 추가로 전송해야 한다.

    response.addCookie(cookie);
    쿠키 생성하기

    아래 폼 JSP 페이지를 실행하는 순간,

    서버는 세션을 유지하기 위해 클라이언트에게 세션ID: JSESSIONID 인 쿠키를 보낸다. 세션을 유지할때도 쿠키를 사용한다는 사실. 웹 브라우저는 현 시점에서 이미 쿠키를 하나 갖는다.

    <%@ page contentType="text/html; charset=utf-8"%>
    <html>
    <head>
    <title>Cookie</title>
    </head>
    <body>
    	<form action="cookie01_process.jsp" method="POST">
    		<p>	아 이 디 : <input type="text" name="id">
    		<p>	비밀번호 : <input type="text" name="passwd">
    		<p>	<input type="submit" value="전송">
    	</form>
    </body>
    </html>

    request 객체의 getParameter를 통해 폼태그에 작성한 아이디 패스워드 값을 가져온다. -> 아이디가 admin, 패스워드가 passwd이면 인증 되었으므로 Cookie cookie = new Cookie("쿠키 식별하기 위한 이름","쿠키 값")으로 쿠키를 생성한다. -> response객체의 addCookie를 사용해 해당 쿠키를 웹 브라우저에게 전송한다. 이렇게 하면 총 원래 있던 JESSIONID쿠키에 +2개의 쿠기가 포함되어 웹 브라우저는 총 3개의 쿠키를 갖는다.

    <%@ page contentType="text/html; charset=utf-8"%>
    <html>
    <head>
    <title>Cookie</title>
    </head>
    <body>
    	<%
    		String user_id = request.getParameter("id");
    		String user_pw = request.getParameter("passwd");
    
    		if (user_id.equals("admin") && user_pw.equals("1234")) {
    			Cookie cookie_id = new Cookie("userID", user_id);
    			Cookie cookie_pw = new Cookie("userPW", user_pw);
    			response.addCookie(cookie_id);
    			response.addCookie(cookie_pw);
    			out.println("쿠기 생성이 성공했습니다<br>");
    			out.println(user_id + "님 환영합니다");
    		} else {
    			out.println("쿠티 생성이 실패했습니다");
    		}
    	%>
    </body>
    </html>

    2. 쿠키 정보

    1. 쿠키 객체 얻기

    • 클라이언트에 저장된 쿠키 객체를 가져올려면 request내장 객체의 getCookies() 메소드를 사용한다.
    • 쿠키 객체가 여러 개일때는 배열 형태로 가져온다.
    Cookie[] cookies = request.getCookies();

     

    2. 쿠키 객체의 정보 얻기

    쿠키 객체를 얻어왔다면, 이 쿠키 객체에 저장된 쿠키 이름과 값을 가져오기 위해 getName()과 getValue()를 이용한다.

    Cookie[] cookies = reqesut.getCookies();
    
    for(int i=0;i<cookies.length;i++){
     out.println(cookies[i].getName() + " : " + cookies[i].getValue() + "<br>");
     }
    쿠키 객체에 저장된 모든 쿠키 값 가져와 출력하기 (ch14/cookie02.jsp)

    출력결과로는 총 3개의 쿠키 이름과 값이 출력된다.

    왜? 처음 서버에 접속시 response객체에 세션ID: JSESSIONID 인 쿠키를 보내기 때문에,

    JSESSIONID, userID, userPW 총 3가지의 쿠키가 출력된다.

    <%@ page contentType="text/html; charset=utf-8"%>
    <html>
    <head>
    <title>Cookie</title>
    </head>
    <body>
    	<%
    		Cookie[] cookies = request.getCookies();
    		out.println("현재 설정된 쿠키의 개수 => " + cookies.length + "<br>");
    		out.println("==========================<br>");
    		for (int i = 0; i < cookies.length; i++) {
    			out.println("설정된 쿠티의 속성 이름 [ " + i + " ] : " + cookies[i].getName() + "<br>");
    			out.println("설정된 쿠키의 속성 값 [ " + i + " ] : " + cookies[i].getValue() + "<br>");
    			out.println("---------------------------------------------<br>");
    		}
    	%>
    </body>
    </html>

    3. 쿠키 삭제

    쿠키 유효 기간을 결정하는 setMaxAge()메소드 값을 0으로 설정하여 쿠키를 삭제할 수 있다.

    1. 쿠키를 생성한 후 -> 2.유효기간을 0으로 설정하고 -> 3.쿠키를 전송하면 ???  == 쿠키가 삭제됨

    Cookie cookie = new Cookie("memberId", "admin");
    cookid.setMaxAge(0);
    response.addCookie(cookie);
    쿠키 객체에 저장된 모든 쿠키 삭제하기

    1. 쿠키의 setMaxAge(0)으로 설정하고 addCookie하여 웹 브라우저가 갖고 있는 모든 쿠키를 삭제한다.

    2. response.sendRedirect("cookie02.jsp); 이 구절에서 갖고 있는 쿠키를 출력하기 위해 cookie02.jsp로 이동한다.

    3. 쿠키를 모두 지웠으므로 하나도 출력되지 않을 것 같지만, 처음 폼태그로 값을 받아온 cookie01.jsp부터 지금까지 아직 웹 브라우저를 닫지 않았기때문에 서버를 최초로 실행했을때 부여된 세션 ID인 JSESSIONID는 유지되고 있다. 그래서 JSESSIONID 쿠키가 출력된다.

     

    foward : 이전페이지 입력버퍼에 썼던 내용을 모두 지우고 다음 페이지 이동한다. 그러나 웹 페이지 주소는 이전 페이지

    sendRedirect : 즉 클라이언트가 새로 페이지를 요청한 것과 같은 방식으로 페이지가 이동하기때문에 이동된 URL이 웹 브라우저의 주소창에보인다

    <%@ page contentType="text/html; charset=utf-8"%>
    <html>
    <head>
    <title>Cookie</title>
    </head>
    <body>
    	<%
    		Cookie[] cookies = request.getCookies();
    
    		for (int i = 0; i < cookies.length; i++) {
    			cookies[i].setMaxAge(0);
    			response.addCookie(cookies[i]);
    		}
    		response.sendRedirect("cookie02.jsp");
    	%>
    </body>
    </html>

     

    [웹 쇼핑몰] 주문 처리 페이지 만들기

    cart.jsp

    - 주문하기 버튼 추가하기

    - 주문하기 버튼누르면 ShippingInfo.jsp 로 이동

    - charId : 세션 아이디

    <td align="right"><a href="./shippingInfo.jsp?cartId=<%=cartId %>" class="btn btn-success">주문하기</a></td>

     

    ShippingInfo.jsp

    - 주문하기 누르면 실행되는 배송정보 페이지

    - 버튼 3개 있음, (이전, 등록, 취소)

    - [이전] cart.jsp로 이동

    - [등록] 버튼 누르면 proceesShippingInfo.jsp 실행 

    - [취소] checkOustCancelled.jsp로 이동

    - hidden 보이지는 않는 carId 세션 아이디

    <%@ page language="java" contentType="text/html; charset=utf-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <link rel ="stylesheet" href ="./resources/css/bootstrap.min.css" />
    <title>배송 정보</title>
    </head>
    <body>
    	<jsp:include page="menu.jsp" />
    	<div class="jumbotron">
    		<div class="container">
    			<h1 class="display-3">배송 정보</h1>
    		</div>
    	</div>
    	<div class="container">
    		<form action="./processShippingInfo.jsp" class="form-horizontal" method="post">
    			<input type="hidden" name="cartId" value="<%=request.getParameter("cartId")%>" />
    			<div class="form-group row">
    				<label class="col-sm-2">성명</label>
    				<div class="col-sm-3">
    					<input name="name" type="text" class="form-control" />
    				</div>
    			</div>
    			<div class="form-group row">
    				<label class="col-sm-2">배송일</label>
    				<div class="col-sm-3">
    					<input name="shippingDate" type="text" class="form-control" />(yyyy/mm/dd)
    				</div>
    			</div>
    			<div class="form-group row">
    				<label class="col-sm-2">국가명</label>
    				<div class="col-sm-3">
    					<input name="country" type="text" class="form-control" />
    				</div>
    			</div>
    			<div class="form-group row">
    				<label class="col-sm-2">우편번호</label>
    				<div class="col-sm-3">
    					<input name="zipCode" type="text" class="form-control" />
    				</div>
    			</div>
    			<div class="form-group row">
    				<label class="col-sm-2">주소</label>
    				<div class="col-sm-5">
    					<input name="addressName" type="text" class="form-control" />
    				</div>
    			</div>
    			<div class="form-group row">
    				<div class="col-sm-offset-2 col-sm-10 ">
    					<a href="./cart.jsp?cartId=<%=request.getParameter("cartId")%>" class="btn btn-secondary" role="button"> 이전 </a> 
    					<input	type="submit" class="btn btn-primary" value="등록" />
    					<a href="./checkOutCancelled.jsp" class="btn btn-secondary" role="button"> 취소 </a>
    				</div>
    			</div>
    		</form>
    	</div>
    </body>
    </html>

    proceesShippingInfo.jsp

    - 서버는 해당정보를 쿠키로 바꾼다-> 클라이언트는 쿠키를 저장(response.add)한다 -> sendRedirect하여 orderConfimation.jsp  웹브라우저 화면에 출력

    - 24시간 쿠키남기도록 setMaxAge 설정

    <%@ page contentType="text/html; charset=utf-8"%>
    <%@ page import="java.net.URLEncoder"%>
    <%
    	request.setCharacterEncoding("UTF-8");
    
    	Cookie cartId = new Cookie("Shipping_cartId", URLEncoder.encode(request.getParameter("cartId"), "utf-8"));
    	Cookie name = new Cookie("Shipping_name", URLEncoder.encode(request.getParameter("name"), "utf-8"));
    	Cookie shippingDate = new Cookie("Shipping_shippingDate",	URLEncoder.encode(request.getParameter("shippingDate"), "utf-8"));
    	Cookie country = new Cookie("Shipping_country",	URLEncoder.encode(request.getParameter("country"), "utf-8"));
    	Cookie zipCode = new Cookie("Shipping_zipCode",	URLEncoder.encode(request.getParameter("zipCode"), "utf-8"));
    	Cookie addressName = new Cookie("Shipping_addressName",	URLEncoder.encode(request.getParameter("addressName"), "utf-8"));
    
    	cartId.setMaxAge(24 * 60 * 60);
    	name.setMaxAge(24 * 60 * 60);
    	zipCode.setMaxAge( 24 * 60 * 60);
    	country.setMaxAge(24 * 60 * 60);
    	addressName.setMaxAge(24 * 60 * 60);
    
    	response.addCookie(cartId);
    	response.addCookie(name);
    	response.addCookie(shippingDate);
    	response.addCookie(country);
    	response.addCookie(zipCode);
    	response.addCookie(addressName);
    
    	response.sendRedirect("orderConfirmation.jsp");
    %>

    orderConfirmation.jsp

    - 설정해놨던 모든 쿠키들을 가져옴, 배열속에 넣고 쿠키 값이 비어있는지 아닌지 확인. 그리고 그 쿠키들 값을 문자열형태로 저장 -> 이걸 이용해 영수증 화면만든다.

    - 표 형태 출력시, 장바구니에서 값을 가져옴.

    -  주문완료 버튼 누르면 thankCustomer.jsp 실행

    -  취소버튼 누르면 checkOutCancelled.jsp 실행

    <%@ page contentType="text/html; charset=utf-8"%>
    <%@ page import="java.util.ArrayList"%>
    <%@ page import="java.net.URLDecoder"%>
    <%@ page import="dto.Product"%>
    <%@ page import="dao.ProductRepository"%>
    
    <%
    	request.setCharacterEncoding("UTF-8");
    
    	String cartId = session.getId();
    
    	String shipping_cartId = "";
    	String shipping_name = "";
    	String shipping_shippingDate = "";
    	String shipping_country = "";
    	String shipping_zipCode = "";
    	String shipping_addressName = "";
    	
    	Cookie[] cookies = request.getCookies();
    
    	if (cookies != null) {
    		for (int i = 0; i < cookies.length; i++) {
    			Cookie thisCookie = cookies[i];
    			String n = thisCookie.getName();
    			if (n.equals("Shipping_cartId"))
    				shipping_cartId = URLDecoder.decode((thisCookie.getValue()), "utf-8");
    			if (n.equals("Shipping_name"))
    				shipping_name = URLDecoder.decode((thisCookie.getValue()), "utf-8");
    			if (n.equals("Shipping_shippingDate"))
    				shipping_shippingDate = URLDecoder.decode((thisCookie.getValue()), "utf-8");
    			if (n.equals("Shipping_country"))
    				shipping_country = URLDecoder.decode((thisCookie.getValue()), "utf-8");
    			if (n.equals("Shipping_zipCode"))
    				shipping_zipCode = URLDecoder.decode((thisCookie.getValue()), "utf-8");
    			if (n.equals("Shipping_addressName"))
    				shipping_addressName = URLDecoder.decode((thisCookie.getValue()), "utf-8");
    		}
    	}
    %>
    <html>
    <head>
    <link rel="stylesheet" href="./resources/css/bootstrap.min.css" />
    <title>주문 정보</title>
    </head>
    <body>
    	<jsp:include page="menu.jsp" />
    	<div class="jumbotron">
    		<div class="container">
    			<h1 class="display-3">주문 정보</h1>
    		</div>
    	</div>
    
    	<div class="container col-8 alert alert-info">
    		<div class="text-center ">
    			<h1>영수증</h1>
    		</div>
    		<div class="row justify-content-between">
    			<div class="col-4" align="left">
    				<strong>배송 주소</strong> <br> 성명 : <% out.println(shipping_name); %>	<br> 
    				우편번호 : <% 	out.println(shipping_zipCode);%><br> 
    				주소 : <%	out.println(shipping_addressName);%>(<%	out.println(shipping_country);%>) <br>
    			</div>
    			<div class="col-4" align="right">
    				<p>	<em>배송일: <% out.println(shipping_shippingDate);%></em>
    			</div>
    		</div>
    		<div>
    			<table class="table table-hover">			
    			<tr>
    				<th class="text-center">도서</th>
    				<th class="text-center">#</th>
    				<th class="text-center">가격</th>
    				<th class="text-center">소계</th>
    			</tr>
    			<%
    				int sum = 0;
    				ArrayList<Product> cartList = (ArrayList<Product>) session.getAttribute("cartlist");
    				if (cartList == null)
    					cartList = new ArrayList<Product>();
    				for (int i = 0; i < cartList.size(); i++) { // 상품리스트 하나씩 출력하기
    					Product product = cartList.get(i);
    					int total = product.getUnitPrice() * product.getQuantity();
    					sum = sum + total;
    			%>
    			<tr>
    				<td class="text-center"><em><%=product.getPname()%> </em></td>
    				<td class="text-center"><%=product.getQuantity()%></td>
    				<td class="text-center"><%=product.getUnitPrice()%>원</td>
    				<td class="text-center"><%=total%>원</td>
    			</tr>
    			<%
    				}
    			%>
    			<tr>
    				<td> </td>
    				<td> </td>
    				<td class="text-right">	<strong>총액: </strong></td>
    				<td class="text-center text-danger"><strong><%=sum%> </strong></td>
    			</tr>
    			</table>
    			
    				<a href="./shippingInfo.jsp?cartId=<%=shipping_cartId%>"class="btn btn-secondary" role="button"> 이전 </a>
    				<a href="./thankCustomer.jsp"  class="btn btn-success" role="button"> 주문 완료 </a>
    				<a href="./checkOutCancelled.jsp" class="btn btn-secondary"	role="button"> 취소 </a>			
    		</div>
    	</div>	
    </body>
    </html>

     

    thankCustomer.jsp

    - "주문해주셔서 감사합니다." + 주문 완료 됐으니까 서버쪽에서는 세션 없애줌(session.invalidate()), 클라이언트가 갖고 있는 쿠기 다 삭제하라는 명령. (setMaxAge(0)) -> response.add()로 전송  -> 클라이언트는 쿠키 다 삭

    <%@ page contentType="text/html; charset=utf-8"%>
    <%@ page import="java.net.URLDecoder"%>
    <html>
    <head>
    <link rel="stylesheet" href="./resources/css/bootstrap.min.css" />
    <title>주문 완료</title>
    </head>
    <body>
    	<%
    		String shipping_cartId = "";
    		String shipping_name = "";
    		String shipping_shippingDate = "";
    		String shipping_country = "";
    		String shipping_zipCode = "";
    		String shipping_addressName = "";		
    
    		Cookie[] cookies = request.getCookies();
    
    		if (cookies != null) {
    			for (int i = 0; i < cookies.length; i++) {
    				Cookie thisCookie = cookies[i];
    				String n = thisCookie.getName();
    				if (n.equals("Shipping_cartId"))
    					shipping_cartId = URLDecoder.decode((thisCookie.getValue()), "utf-8");
    				if (n.equals("Shipping_shippingDate"))
    					shipping_shippingDate = URLDecoder.decode((thisCookie.getValue()), "utf-8");
    			}
    		}
    	%>
    	<jsp:include page="menu.jsp" />
    	<div class="jumbotron">
    		<div class="container">
    			<h1 class="display-3">주문 완료</h1>
    		</div>
    	</div>
    	<div class="container">
    		<h2 class="alert alert-danger">주문해주셔서 감사합니다.</h2>
    		<p>	주문은	<%	out.println(shipping_shippingDate);	%>에 배송될 예정입니다! !	
    		<p>	주문번호 :	<%	out.println(shipping_cartId);	%>		
    	</div>
    	<div class="container">
    		<p>	<a href="./products.jsp" class="btn btn-secondary"> &laquo; 상품 목록</a>		
    	</div>
    </body>
    </html>
    <%
    	session.invalidate();
    
    	for (int i = 0; i < cookies.length; i++) {
    		Cookie thisCookie = cookies[i];
    		String n = thisCookie.getName();
    		if (n.equals("Shipping_cartId"))
    			thisCookie.setMaxAge(0);
    		if (n.equals("Shipping_name"))
    			thisCookie.setMaxAge(0);
    		if (n.equals("Shipping_shippingDate"))
    			thisCookie.setMaxAge(0);
    		if (n.equals("Shipping_country"))
    			thisCookie.setMaxAge(0);
    		if (n.equals("Shipping_zipCode"))
    			thisCookie.setMaxAge(0);
    		if (n.equals("Shipping_addressName"))
    			thisCookie.setMaxAge(0);
    		
    		response.addCookie(thisCookie);
    	}
    %>

     

    checkOutCancelled.jsp

    - "주문이 취소되었습니다."

    <%@ page contentType="text/html; charset=utf-8"%>
    <html>
    <head>
    <link rel="stylesheet" href="./resources/css/bootstrap.min.css" />
    <title>주문 취소</title>
    </head>
    <body>
    	<jsp:include page="menu.jsp" />
    	<div class="jumbotron">
    		<div class="container">
    			<h1 class="display-3">주문 취소</h1>
    		</div>
    	</div>
    	<div class="container">
    		<h2 class="alert alert-danger">주문이 취소되었습니다.</h2>
    	</div>
    	<div class="container">
    		<p><a href="./products.jsp" class="btn btn-secondary"> &laquo; 상품 목록</a>		
    	</div>	
    </body>
    </html>

    'jsp' 카테고리의 다른 글

    MYSQL 기본명령어  (0) 2023.05.31
    HTTP,쿠키,세션  (1) 2023.05.30
    [jsp] 유효성 검사  (3) 2023.04.25
    [jsp] 파일 업로드  (0) 2023.04.25
    [jsp] 폼 태그  (0) 2023.04.25

    댓글

lee-ding