11/23 49-2 [JSP] Cookie연습(장바구니담기)
우리가 사이트에서 로그인 할 때 아이디 저장에 체크하면 아이디를 자동으로 저장시키는 기능이 있는데
그게 쿠키를 이용한 거였음!!
그리고 장바구니를 담아놓고 유지하는 것도 바로 이 쿠키를 이용한 기술 이었다!!
그걸.... 구현 해 보고자 함
1. 장바구니담기 예제
크게보자.... 이거 계속 왔다갔다 해서 정신없는데
우선 장바구니는 4개의 페이지가 필요함
먼저 상품들이 나열되어있는 페이지
장바구니에 담는 로직을 짜는 페이지 (얘는 바로 이동시킬 페이지임)
담긴 장바구니를 보여주는 페이지
장바구니를 비우는 로직을 짜는 페이지(얘도 바로 이동시킬 페이지임)
[1. 상품들이나열되어 있는 페이지 파일을 보자 코드가 이미 적혀있지만 HTML만 보고 크게 구상해 !]
CookieExamIndex.jsp
<form action="CookieExamCartProcess.jsp">
<div class="form-group">
<div class="d-flex">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" name="cart" value="product1" id="product1" <% if(cart.contains("product1")){%> checked disabled<%}%> >
<label class="custom-control-label" for="product1">상품1</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" name="cart" value="product2" id="product2" <% if(cart.contains("product1")){%> checked disabled<%}%>>
<label class="custom-control-label" for="product2">상품2</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" name="cart" value="product3" id="product3" <% if(cart.contains("product3")){%> checked disabled<%}%> >
<label class="custom-control-label" for="product3">상품3</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" name="cart" value="product4" id="product4" <% if(cart.contains("product4")){%> checked disabled<%}%>>
<label class="custom-control-label" for="product4">상품4</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" name="cart" value="product15" id="product15" <% if(cart.contains("product15")){%> checked disabled<%}%> >
<label class="custom-control-label" for="product15">상품15</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" name="cart" value="product190" id="product190"<% if(cart.contains("product190")){%> checked disabled<%}%>/>
<label class="custom-control-label" for="product190">상품190</label>
</div>
<input type="submit" value="장바구니 담기" class="btn btn-info"/>
</div>
</div>
</form>
<form action="CookieExamCartEmpty.jsp">
<input type="submit" value="장바구니 비우기" class="btn btn-info"/>
</form>
<hr/>
<a href="CookieExamCartShow.jsp" class="btn btn-info">장바구니 보기</a>

상품들의 체크박스를 체크해서 장바구니 담기를 누르면
순서는 이렇게 짬
1.장바구니 담는 로직의 페이지로 가서 로직처리 후 다시 돌아올 거
2.그러면 장바구니 담긴 것들은 체크 처리가 될 거고
3.장바구니 보기를 누르면 그 페이지로 이동해서 체크된 상품들을 보여줄거
4.다시돌아와서 장바구니 비우기를 누르면 체크된 것들을 해제시킨다 !
[2. 그럼 장바구니 넣기 페이지 코드를 짜보자]
CookieExamCartProcess.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- CookieExamCartProcess.jsp -->
<%@ include file="/common/Validate.jsp" %> <!-- 아무것도 안담았을 때의 유효성 체크할 것!--->
<%
// 장바구니에 담을 상품 코드받기 여러개를 받을 수 있으니 배열로받기!
//param으로 받는건 위에서 name="" 명으로 얻는 것 이구나 !
String[] codes = request.getParameterValues("cart");
if(!isValidate(out,codes,1)) return; //서버단에서 체크 1개이상 담기!
//상품코드를 쿠키로 저장. 즉, 사용자 브라우저에 상품코드 저장
for(String code : codes){
Cookie cookie = new Cookie(code,code); //코드명을 name과 value로 지정
cookie.setPath(request.getContextPath());
//응답헤더에 설정
response.addCookie(cookie);
}
//상품 목록페이지로 이동 요청해서 들어왔으니 바로 응답해야해서 응답객체&리다이렉트로 !
response.sendRedirect("CookieExamIndex.jsp");
%>
[만든 쿠키를 응답헤더로 보냈으니 받아서 쿠키값을 뿌려야지 !!!]
CookieExamIndex.jsp
<%
//요청 헤더에서 쿠키값 읽기
Cookie[] cookies = request.getCookies();
//상품 코드값을 담을 컬렉션
List<String> cart = new Vector<>();
if(cookies != null){
for(Cookie cookie : cookies){
String name = cookie.getName();
String value = cookie.getValue();
if(name.indexOf("product") !=-1 ) cart.add(value);
}
}
%>

[3.장바구니보기 페이지로 가서 체크된 객체들을 뿌려주쟈!]
CookieExamCartShow.jsp
상품명들을 담을 String 객체 먼저 생성,
상품코드들을 쿠키로 저장 했으니 저장한 내용들을 뿌려주자!
뿌릴 때 코드들을 알아보기 쉽게 상품명으로 변경한게 선언부에서 한 일 !
근데 name.indexOf("product") != -1 의 의미를 잘 모르겠음... 아이 멍충아 해당인덱스가 존재하지 않을 때 음수나 0 반환하잖아!! 그거로 체크 한거네 !
//선언부에서 상품명을 담을 String 변수선언
<%!
private String getProductName(String code){
return code.replace("product","상품");
}
%>
//장바구니에 담은 상품들을 뿌려주자!
<ul class="list-unstyled">
<%
//요청 헤더에서 쿠키값 읽기 클릭해서 들어올 거니까 요청할거 아님?
Cookie[] cookies = request.getCookies();
//상품 코드값을 담을 컬렉션
if(cookies != null){
for(Cookie cookie:cookies){
//쿠키명 얻기
String name=cookie.getName();
//쿠키값 얻기
String value=cookie.getValue();
//장바구니용
if(name.indexOf("product") != -1 )
out.println(String.format("<li>%s</li>",getProductName(value)));
}
}
%>
</ul>
<a href="CookieExamIndex.jsp" class="btn but-info">계속 쇼핑하기</a>

[4.대망의 장바구니 비우기 !!]
CookieExamCartEmpty.jsp
여기서 쿠키를 삭제하는걸 배우게 될 것임 !
저장되어있는 쿠키들을 빈 문자열로 처리 후 다시 저장하는 메커니즘?
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- - CookieExamCartEmpty.jsp--->
<%
Cookie[] cookies = request.getCookies();
if(cookies != null){ // null체크
for(Cookie cookie : cookies){
//쿠키명 얻기
String name = cookie.getName();
//쿠키값 얻기
String value = cookie.getValue();
//장바구니용
if(name.indexOf("product") !=-1 ){
//쿠키삭제처리
//1.동일한 쿠키명으로 쿠키생성, 쿠키값은 빈 문자열로 만들고
Cookie cook=new Cookie(name,"");
cook.setPath(request.getContextPath());
//유효기간은 0이나 -값으로 설정
cook.setMaxAge(0);
//3.다시 응답헤더에 추가
response.addCookie(cook);
}
}
}
//상품목록 페이지로 이동
response.sendRedirect("CookieExamIndex.jsp");
%>
