[쉽게 배우는 JSP 웹 프로그래밍] 14장 정리, 연습문제

쿠키 생성, 정보 추출, 삭제 방법에 대한 내용을 다루었습니다. 쿠키 생성은 Cookie 클래스와 addCookie() 메소드를 사용하며, 쿠키 정보는 getCookie() 메소드와 getName(), getValue() 메소드를 사용해 얻습니다. 쿠키 삭제는 setMaxAge() 메소드에 유효 기간을 0으로 설정함으로써 이루어집니다. 이러한 개념들은 실제 웹 페이지에서 로그인, 장바구니, 주문 정보 등을 처리하는 예제를 통해 실습하였습니다.
Feb 29, 2024
[쉽게 배우는 JSP 웹 프로그래밍] 14장 정리, 연습문제

쿠키 생성

cookie01.jsp

<%@ 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>

cookie01_process.jsp

<%@ 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>
 

핵심 키워드

  • 쿠키를 사용하려면 먼저 Cookie 클래스를 사용하여 쿠키를 생성해야 한다.
    • Cookie() 메소드를 이용해서 쿠키를 생성할 수 있다.
  • 쿠키를 생성한 후에는 반드시 response 내장 객체의 addCookie() 메소드로 쿠키를 설정해야 한다.
 

쿠키 정보

cookie02.jsp

<%@ 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>
 

핵심 키워드

  • 생성된 쿠키의 정보를 얻어오려면 request 내장 객체의 getCookie() 메소드를 사용하여 쿠키 객체를 얻어온 후 getName(), getValue() 메소드를 사용하여 쿠키 이름과 값을 얻어온다.
 

쿠키 삭제

cookie03.jsp

<%@ 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>
 

핵심 키워드

  • Cookie 클래스는 쿠키를 삭제하는 기능을 별도로 제공하지 않으며, 쿠키를 더 유지할 필요가 없으면 쿠키의 유효 기간을 만료하면 된다.
    • 쿠키의 유효 기간을 결정하는 setMaxAge() 메소드에 유효 기간을 0으로 설정하여 쿠키를 삭제할 수 있다.
 

연습문제

practice01.jsp

01 response 내장 객체의 addCookie() 메소드로 쿠키를 설정할 수 있다. 설정한 쿠키는 response 내장 객체의 getCookie() 메서드로 쿠키 정보를 얻어올 수 있다. 02 쿠키를 더 유지할 필요가 없으면 setMaxAge() 메소드에 유효 기간을 0으로 설정하여 쿠키를 삭제할 수 있다.

practice03.jsp

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

practice03_process.jsp

<%@ 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); response.addCookie(cookie_id); response.sendRedirect("practice03_welcome.jsp"); }else{ response.sendRedirect("practice03.jsp"); } %> </body> </html>

practice03_welcome.jsp

<%@ page contentType="text/html; charset=utf-8"%> <% Cookie[] cookies = request.getCookies(); String userId = ""; for (int i = 0; i < cookies.length; i++) { if(cookies[i].getName().equals("userID")){ userId = cookies[i].getValue(); } } if (userId == null) { response.sendRedirect("practice03_cookie_out.jsp"); } %> <h3><%=userId%>님 반갑습니다. </h3> <a href="practice03_cookie_out.jsp">로그아웃</a>

practice03_cookie_out.jsp

<%@ page contentType="text/html; charset=utf-8"%> <% session.invalidate(); Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie thisCookie = cookies[i]; String n = thisCookie.getName(); if (n.equals("userID")) thisCookie.setMaxAge(0); response.addCookie(thisCookie); } response.sendRedirect("practice03.jsp"); %>

practice04

cart.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.util.ArrayList"%> <%@ page import="dto.Book"%> <%@ page import="dao.BookRepository"%> <html> <head> <link rel="stylesheet" href="./resources/css/bootstrap.min.css" /> <% String cartId = session.getId(); %> <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"> <div class="row"> <table width="100%"> <tr> <td align="left"><a href="./deleteCart.jsp?cartId=<%=cartId%>" class="btn btn-danger">삭제하기</a></td> <td align="right"><a href="./shippingInfo.jsp?cartId=<%=cartId%>" class="btn btn-success">주문하기 </a></td> </tr> </table> </div> <div style="padding-top: 50px"> <table class="table table-hover"> <tr> <th>상품</th> <th>가격</th> <th>수량</th> <th>소계</th> <th>비고</th> </tr> <% int sum = 0; ArrayList<Book> cartList = (ArrayList<Book>) session.getAttribute("cartlist"); if (cartList == null) cartList = new ArrayList<Book>(); for (int i = 0; i < cartList.size(); i++) { // 상품리스트 하나씩 출력하기 Book book = cartList.get(i); int total = book.getUnitPrice() * book.getQuantity(); sum = sum + total; %> <tr> <td><%=book.getBookId()%> - <%=book.getName()%></td> <td><%=book.getUnitPrice()%></td> <td><%=book.getQuantity()%></td> <td><%=total%></td> <td><a href="./removeCart.jsp?id=<%=book.getBookId()%>" class="badge badge-danger">삭제</a></td> </tr> <% } %> <tr> <th></th> <th></th> <th>총액</th> <th><%=sum%></th> <th></th> </tr> </table> <a href="./books.jsp" class="btn btn-secondary"> &laquo; 쇼핑 계속하기</a> </div> <hr> </div> <jsp:include page="footer.jsp" /> </body> </html>

shippingInfo.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"> <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>

processShippingInfo.jsp

<%@ 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

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.util.ArrayList"%> <%@ page import="java.net.URLDecoder"%> <%@ page import="dto.Book"%> <%@ page import="dao.BookRepository"%> <% 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<Book> cartList = (ArrayList<Book>) session.getAttribute("cartlist"); if (cartList == null) cartList = new ArrayList<Book>(); for (int i = 0; i < cartList.size(); i++) { Book product = cartList.get(i); int total = product.getUnitPrice() * product.getQuantity(); sum = sum + total; %> <tr> <td class="text-center"><em><%=product.getName()%></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>

thankCustumer.jsp

<%@ 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="./books.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="./books.jsp" class="btn btn-secondary"> &laquo; 상품 목록</a> </div> </body> </html>
 

결론

해당 코드를 작성하면서 쿠키의 개념, 쿠키 생성 방법, 쿠키 정보를 얻어오는 방법, 쿠키를 삭제하는 방법을 익힐 수 있었다.
Share article

More articles

See more posts
RSSPowered by inblog