스프링 (26)

반응형

 

다운로드

 

 

1

 

1. 아래의 홈페이지에 접속 > 다운로드 > 개발환경 클릭 > 3.x다운로드 클릭

https://www.egovframe.go.kr/home/sub.do?menuNo=41

 

개발환경 - 3.x 다운로드 | 표준프레임워크 포털 eGovFrame

처리중입니다. 잠시만 기다려주십시오.

www.egovframe.go.kr

 

2

 

2. 개발자용 클릭 > 첨부파일 클릭 > 다운로드 클릭

 

3

 

3. C드라이브에 파일 넣기

 

4

 

4. 자바 버전 확인(1.8이어야 함)

 

5

 

5. 파일 압축 풀기

 

반응형

'스프링' 카테고리의 다른 글

[스프링] 22.5장 과제  (0) 2024.04.18
[스프링] 22장 쇼핑몰 시스템8, 쿠키 생성  (1) 2024.04.18
[스프링] 21장 세션  (1) 2024.04.18
[스프링] 20장 과제  (0) 2024.04.17
[스프링] 19장 필터, 쇼핑몰 시스템7  (0) 2024.04.17
반응형

 

연습 문제 01

 

세션이란 무엇인가?

 

더보기

클라이언트와 웹 서버 간의 상태를 지속적으로 유지하는 방법

 

 

 

연습 문제 02

 

JSP 페이지에 세션을 설정하는 메소드, 설정된 세션을 삭제하는 메소드는 무엇인가?

 

더보기

setAttribute(), removeAttribute(), invalidate()

 

 

 

연습 문제 03

 

설정된 세션 정보를 얻어오는 메소드에 대해 간단히 설명하시오.

 

더보기

getAttribute(String name)

: 단일의 세션 정보를 가져온다.

name인 세션 속성을 가져옴, Object 형으로 반환하므로 형 변환하여 사용해야 함

 

 

getAttributeNames()

: 다중의 세션 정보를 가져온다.

모든 세션 속성의 이름과 속성 값을 얻어옴

Enumeration enum = session.getAttributeNames();

While(enum.hasMoreElements()) {
	String name = enum.nextElement().toString();
    String value = session.getAttribute(name).toString();
}

 

 

 

연습 문제 04

 

세션을 이용하여 다음 조건에 맞게 JSP 애플리케이션을 만들고 실행 결과를 확인하시오.

 

 

 

더보기

session.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<form action="session_process.jsp" method="post">
		<p>아 이 디 : <input type="text" name="id" placeholder="아이디" required></p>
		<p>비밀번호 : <input type="text" name="passwd" placeholder="비밀번호" required></p>
		<p><input type="submit" value="전송"></p>
	</form>
</body>
</html>

 

 

session_process.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<%
		String user_id = request.getParameter("id");
		String user_pw = request.getParameter("passwd");
		
		System.out.println("user_id >> " + user_id);
		System.out.println("user_pw >> " + user_pw);
		if(user_id.equals("admin") && user_pw.equals("admin1234")) {
			// 세션에 값 저장
			session.setAttribute("userID", user_id);
			session.setAttribute("userPW", user_pw);
			
			out.print("세션 설정 성공<br />");
			out.print(user_id + "님 환영합니다.");
		} else {
			out.print("세션 설정 실패!");
		}
		response.sendRedirect("welcome.jsp");
	%>
</body>
</html>

 

 

welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<%
		String user_id = (String)session.getAttribute("userID");
		String user_pw = (String)session.getAttribute("userPW");
		
		if(user_id == null || user_id.equals("")) {
			response.sendRedirect("session_out.jsp");
		}
		
		out.print("<p>" + user_id + "님 반갑습니다.</p>");
	%>
	
	<p><a href="session_out.jsp" >로그아웃</a></p>
</body>
</html>

 

 

session_out.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<%
		session.invalidate();
		response.sendRedirect("session.jsp");
	%>
</body>
</html>

 

결과 화면1

 

결과 화면2

 

 

 

연습 문제 05

 

다음 조건에 맞게 도서 웹 쇼핑몰을 위한 웹 애플리케이션을 만들고 실행 결과를 확인하시오.

 

 

 

 

 

반응형
반응형

 

상품 추가 : 핸들러 함수 추가

 

product.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="kr.or.ddit.vo.ProductVO"%>
<%@ page import="kr.or.ddit.dao.ProductRepository"%>
<%@ page errorPage="/exceptionNoPage.jsp" %>
<%
	/*
	요청URI : product.jsp
	요청파라미터 : productId=P1234
	요청방식 : get(목록, 검색, 상세)
	*/
	// 싱글톤
	ProductRepository productDAO = 
		ProductRepository.getInstance();
	
	String productId = request.getParameter("productId"); // P1234
	out.print("<p>"+productId+"</p>"); // P1234
	
	ProductVO productVO = productDAO.getProductById(productId);
	out.print("<p>"+productVO+"</p>");
	
	productVO.toString(); //?productId=P000 => null.toString() => 문제 발생
%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
<script type="text/javascript">
	// 핸들러 함수
	function addToCart() {
// 		console.log("개똥이");
		if(confirm("상품을 장바구니에 추가하시겠습니까?")) {
			console.log("네");
			// /addCart.jsp?productId=P1234
			// 폼을 submit
			document.addForm.submit();
			
		} else {
			console.log("아니오");
			// 폼 안의 폼데이터를 초기화
			document.addForm.reset();
		}
	}
</script>
</head>
<body>
	<!-- include 액션 태그 -->
	<jsp:include page="menu.jsp" /> <!-- 파라미터가 없기 때문에 이렇게 사용 가능 -->

	<!-- --------------------상품상세 시작-------------------- -->
	<div class="jumbotron">
	   <!-- container : 이 안에 내용있다 -->
	   <div class="container">
	      <h1 class="display-3">상품 정보</h1>
	   </div>
	</div>
	<!-- 내용 -->
	<div class="container">
		<div class="row">
			<div class="col-md-5">
				<img src="/images/<%=productVO.getFilename()%>" 
					style="width:100%;">
			</div>
			<div class="col-md-6">
				<h3><%=productVO.getPname()%></h3>
				<p><%=productVO.getDescription()%></p>
				<p>
					<b>상품 코드 : </b>
					<span class="badge bage-danger">
					<%=productVO.getProductId()%>
					</span>
				</p>
				<p><b>제조사 : </b><%=productVO.getManufacturer()%></p>
				<p><b>분류 : </b><%=productVO.getCategory()%></p>
				<p><b>재고 수 : </b><%=productVO.getUnitsInStock()%></p>
				<h4><%=productVO.getUnitPrice()%></h4>
				<p>
					<!-- 폼태그, 폼페이지 
					action : 요청URI
					요청URI : addCart.jsp
					요청파라미터 : id=P1234
					요청방식 : post
					-->
					<form name="addForm" action="addCart.jsp?productId=<%=productVO.getProductId()%>"
						method="post">
						<!-- 폼데이터 -->
						<!-- 상품 주문 : 장바구니에 상품을 넣음 
						addToCart() : 핸들러 함수
						-->
						<a href="#" class="btn btn-info" onclick="addToCart()">상품주문&raquo;</a>
						<!-- 장바구니 : 장바구니에 담겨진 상품 목록 확인 -->
						<a href="cart.jsp" class="btn btn-warning">장바구니&raquo;</a>
						<a href="products.jsp" class="btn btn-secondary">상품 목록&raquo;</a>
					</form>
			</div>
		</div>
	</div>
	
	<jsp:include page="footer.jsp" />
</body>
</html>

 

 

addCart.jsp

<%@page import="java.util.ArrayList"%>
<%@page import="kr.or.ddit.vo.ProductVO"%>
<%@page import="kr.or.ddit.dao.ProductRepository"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!-- 폼태그, 폼페이지 
action : 요청URI
요청URI : addCart.jsp
요청파라미터 : {productId=P1234}
요청방식 : post
-->
<%
	request.setCharacterEncoding("UTF-8");

	String id = request.getParameter("productId");
	
	out.print("id : " + id + "<br />");
	
	// addCart.jsp or addCart.jsp?productId = 
	// products.jsp로 redirect
	if(id == null || id.trim().equals("")) {
		// 새로운 UFL을 재요청
		response.sendRedirect("/products.jsp");
		return; // 아래 쪽은 실행 안 함
	}
	
	//기본키인 P1234 코드의 상품을 찾아보자
	//ProductRepository 싱글톤 패턴으로 공유된 객체 생성
	ProductRepository dao = ProductRepository.getInstance();
	
	//select * from product
	//where product_id='P1234'
	ProductVO productVO = dao.getProductById(id);
	
	//상품 결과가 없으면
	if(productVO == null){
	   //[상품이 없음]예외처리 페이지로 이동
	   response.sendRedirect("exceptionNoProductId.jsp");
	}else{
	   
	}
	
	// 장바구니(세션) => 세션 속성명 : cartlist
	ArrayList<ProductVO> list = (ArrayList<ProductVO>)session.getAttribute("cartlist");
	
	// 장바구니가 없으면 생성
	if(list == null) {
		list = new ArrayList<ProductVO>();
		session.setAttribute("cartlist", list);
	}
	
	//장바구니가 있다면 다음을 실행
	int cnt = 0;
	
	//1)장바구니에 P1234 상품이 이미 들어있는 경우
	//    private int quantity;   //상품을 장바구니에 담은 개수
	//   quantity를 1 증가
	//2)장바구니에 P1234 상품이 없는 경우
	//  장바구니에 상품을 넣어주고
	//   quantity를 1로 처리
	//list : 장바구니에 들어있는 상품 목록
	for(int i=0;i<list.size();i++){
	   //list는 장바구니(P1234,P1235,P1236)
	   //list.get(0).getProductId().equals("P1234")
	   if(list.get(i).getProductId().equals(id)){
	      cnt++;
	      //장바구니에 상품이 이미 들어있다면 장바구니에 담은 개수만 1 증가
	      list.get(i).setQuantity(list.get(i).getQuantity()+1);
	   }
	}
	
	//장바구니에 해당 상품이 없다면
	if(cnt == 0){
	   productVO.setQuantity(1);
	   //최종목표 : 장바구니(list)에 상품을 추가
	   list.add(productVO);
	}
	
	//장바구니 확인
	for(ProductVO pd : list){
	   out.print("pd : " + pd.toString() 
	      + "<br /><hr />");
	}
%>

 

결과 화면1

 

 

=> sendRedirect 추가

<%@page import="java.util.ArrayList"%>
<%@page import="kr.or.ddit.vo.ProductVO"%>
<%@page import="kr.or.ddit.dao.ProductRepository"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!-- 폼태그, 폼페이지 
action : 요청URI
요청URI : addCart.jsp
요청파라미터 : {productId=P1234}
요청방식 : post
-->
<%
	request.setCharacterEncoding("UTF-8");

	String id = request.getParameter("productId");
	
	out.print("id : " + id + "<br />");
	
	// addCart.jsp or addCart.jsp?productId = 
	// products.jsp로 redirect
	if(id == null || id.trim().equals("")) {
		// 새로운 UFL을 재요청
		response.sendRedirect("/products.jsp");
		return; // 아래 쪽은 실행 안 함
	}
	
	//기본키인 P1234 코드의 상품을 찾아보자
	//ProductRepository 싱글톤 패턴으로 공유된 객체 생성
	ProductRepository dao = ProductRepository.getInstance();
	
	//select * from product
	//where product_id='P1234'
	ProductVO productVO = dao.getProductById(id);
	
	//상품 결과가 없으면
	if(productVO == null){
	   //[상품이 없음]예외처리 페이지로 이동
	   response.sendRedirect("exceptionNoProductId.jsp");
	}else{
	   
	}
	
	// 장바구니(세션) => 세션 속성명 : cartlist
	ArrayList<ProductVO> list = (ArrayList<ProductVO>)session.getAttribute("cartlist");
	
	// 장바구니가 없으면 생성
	if(list == null) {
		list = new ArrayList<ProductVO>();
		session.setAttribute("cartlist", list);
	}
	
	//장바구니가 있다면 다음을 실행
	int cnt = 0;
	
	//1)장바구니에 P1234 상품이 이미 들어있는 경우
	//    private int quantity;   //상품을 장바구니에 담은 개수
	//   quantity를 1 증가
	//2)장바구니에 P1234 상품이 없는 경우
	//  장바구니에 상품을 넣어주고
	//   quantity를 1로 처리
	//list : 장바구니에 들어있는 상품 목록
	for(int i=0;i<list.size();i++){
	   //list는 장바구니(P1234,P1235,P1236)
	   //list.get(0).getProductId().equals("P1234")
	   if(list.get(i).getProductId().equals(id)){
	      cnt++;
	      //장바구니에 상품이 이미 들어있다면 장바구니에 담은 개수만 1 증가
	      list.get(i).setQuantity(list.get(i).getQuantity()+1);
	   }
	}
	
	//장바구니에 해당 상품이 없다면
	if(cnt == 0){
	   productVO.setQuantity(1);
	   //최종목표 : 장바구니(list)에 상품을 추가
	   list.add(productVO);
	}
	
	//장바구니 확인
	for(ProductVO pd : list){
	   out.print("pd : " + pd.toString() 
	      + "<br /><hr />");
	}
	
	response.sendRedirect("product.jsp?productId="+id);
%>

 

 

 

장바구니 추가

 

 

cart.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="java.util.Date"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
   href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<title>Welcome</title>
</head>
<body>
	<!-- 머리글에 해당하는 menu.jsp 파일의 내용이 포함되도록 include 디렉티브 태그를 작성 -->
	<%@ include file="menu.jsp" %>
	
	<%
		// 세션의 고유 아이디(장바구니 번호). 하나의 웹브라우저
		String cartId = session.getId();
		
		out.print("cartId : " + cartId);
	%>
	<c:set var="cartId" value="<%=cartId%>" />
	
	<!-- session.setAttribute("cartlist", list); -->
	<c:set var="cartlist" value="${sessionScope.cartlist}" />
	<p>${cartlist}</p>
	
	<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;">
			<p></p>
			<table class="table table-hover">
				<tr>
					<th>상품</th><th>가격</th><th>수량</th>
					<th>금액</th><th>비고</th>
				</tr>
				
				<!-- 장바구니가 비어있다면 -->
				<c:if test="${fn:length(cartlist)== 0}" >
					<tr style="text-align:center;">
						<td colspan="5" style="text-align: center;">장바구니에 상품이 없습니다.</td>
					</tr>
				</c:if>
				<c:if test="${fn:length(cartlist)>0}">
					
					<!-- 
					forEach 태그? 배열(String[], int[][]), Collection(List, Set) 또는 
					Map(HashTable, HashMap, SortedMap)에 저장되어 있는 값들을 
					순차적으로 처리할 때 사용함. 자바의 for, do~while을 대신해서 사용함
					var : 변수
					items : 아이템(배열, Collection, Map)
					varStatus : 루프 정보를 담은 객체 활용
					   - index : 루프 실행 시 현재 인덱스(0부터 시작)
					   - count : 실행 회수(1부터 시작. 보통 행번호 출력)
					 -->
					<!-- list : List<ProductVO> -->
					<c:forEach var="productVO" items="${cartlist}" varStatus="stat">
						<!-- amt = amt + 금액 -->
						<c:set var="amt" value="${amt + productVO.unitPrice*productVO.quantity}" />
						<tr>
							<td>${productVO.productId}-${productVO.pname}</td>
							<!-- fmt:formatNumber은 숫자형태의 값을 다양한 포맷에 맞게 출력해줌 -->
							<td><fmt:formatNumber value="${productVO.unitPrice}" pattern="#,###" /></td>
							<td><fmt:formatNumber value="${productVO.quantity}" /></td>
							<td><fmt:formatNumber value="${productVO.unitPrice*productVO.quantity}" pattern="#,###" /></td>
							<td>삭제</td>
						</tr>
					</c:forEach>
					<tr>
						<th></th>
						<th></th>
						<th>총액</th>
						<th><fmt:formatNumber value="${amt}" pattern="#,###" /></th>
						<th></th>
					</tr>
				</c:if>
			</table>
			<a href="products.jsp" class="btn btn-secondary">&laquo;쇼핑 계속하기</a>
		</div>
		<!-- /////장바구니 출력 끝///// -->
	</div>
	
	<!-- 표현문 -->
	<%@ include file="footer.jsp" %>

</body>
</html>

 

 

+ 전에 했던 코드 오류 수정!

menu.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%	// 스크립틀릿
	// 시큐리티의 사용자명을 가져옴
	String username = request.getRemoteUser();
// 	out.print("username : " + username + "<br />");
%>
<!-- JAVA세계의 변수 username의 값을 JSTL세계의 변수 username에 할당 -->
<c:set var="username" value="<%=username%>" />
<nav class="navbar navbar-expand navbar-dark bg-dark">
	<div class="container">
		<div class="navbar-header" style="width:100%;">
			<!-- 요청 URL : /welcome.jsp -->
			<div style="float:le28ft;">
				<a class="navbar-brand" href="welcome.jsp">Home</a>
			</div>
		</div>
		<div style="float:right;">
            <span class="navbar-brand">
               <!-- 로그인 했음 -->
               <c:if test="${fn:length(username)>0}">
                  ${username}님 환영합니다. | 
                  <a href="/logout.jsp" class="btn btn-sm btn-success pull-right">logout</a>
               </c:if>
               <!-- 로그인 안함 -->
               <c:if test="${fn:length(username)==0}">
                  <a href="addProduct.jsp">로그인해주세요.</a>
               </c:if>
            </span>
         </div>
	</div>
</nav>

 

결과 화면2

 

 

 

장바구니 삭제

 

 

deleteCart.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
	//스크립틀릿
	//요청URI : /deleteCart.jsp?cartId=CF61A1B17D9247CFCA3D6B33E48528A6
	//요청파라미터 : cartId=CF61A1B17D9247CFCA3D6B33E48528A6
	//session.getId() : 세션고유아이디 = 고유장바구니 = 동일웹브라우저 = 1명의고객
	String id = request.getParameter("cartId"); //CF61A1B17D9247CFCA3D6B33E48528A6
	
	//id가 없다면? => cart.jsp로 이동
	if(id==null || id.trim().equals("")) {
		response.sendRedirect("cart.jsp");
	}
	
	//id가 있다면 장바구니를 비우기
	//session.invalidate();
	session.removeAttribute("cartlist");
	
	//cart.jsp로 이동
	response.sendRedirect("cart.jsp");
%>

 

결과 화면3

 

 

 

주문하기

 

 

shippingInfo.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="java.util.Date"%>
<!-- 
골뱅이(디렉티브) page 
contentType : 컨텐츠 유형 => html
charset : 문자열 세트 => UTF-8로 설정
-->
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
   href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<title>Welcome</title>
</head>
<body>
   <%@ include file="/menu.jsp"%>

   <div class="jumbotron">
      <div class="container">
         <h1 class="display-3">배송 정보</h1>
      </div>
   </div>
   <!-- /shippingInfo.jsp?cartId=52B70B41FAF308F0E171D98FB2A2BFDC
      요청URI :/processShippingInfo.jsp
      요청파라미터:{name=개똥이,shippingDeta =2024-04-22,country=대한}
    -->
   <div class="container">
      <form action="processShippingInfo.jsp" method="post" class="form-horizontal">
         <input type="text" name="cartId" value="<%=request.getParameter("cartId") %>" />
            <div class="form-group row">
            <label class="col-sm-2">성명</label>
            <div class="col-sm-3">
               <input type="text" name="name" class="form-control" />
            </div>
         </div>
         <div class="form-group row">
            <label class="col-sm-2">배송일</label>
            <div class="col-sm-3">
               <input type="date" name="shippingDate" 
               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 type="text" name="country" 
               class="form-control" />
            </div>
         </div>
         <div class="form-group row">
            <label class="col-sm-2">우편번호</label>
            <div class="col-sm-3">
               <input type="text" name="zipCode" 
               class="form-control" />
            </div>
         </div>
         <div class="form-group row">
            <label class="col-sm-2">주소</label>
            <div class="col-sm-3">
               <input type="text" name="addressName" 
               class="form-control" />
            </div>
         </div>
         <div class="form-group row">
            <div class="col-sm-offset-2 col-sm-10">
            <!-- /shippingInfo.jsp?cartId=52B70B41FAF308F0E171D98FB2A2BFDC -->
               <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>
   
   <!-- footer영역 -->
   <%@ include file="/footer.jsp"%>
</body>
</html>

 

결과 화면4

 

 

processShippingInfo.jsp

<%@page import="java.net.URLEncoder"%>
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!--  
	요청URI : /processShippingInfo.jsp
	요청파라미터 : {cartId=sdfseef,name=개똥이,shippingDate=2024-04-22,
				country=대한민국,zipCode=12345,addressName=대전 중구 선화동123}
	요청방식 : post
-->
<%
	request.setCharacterEncoding("UTF-8");

	// 요청 파라미터 정보를 쿠키에 넣음
	// en{name, shippingDate, country, zipCode, addressName}
	Enumeration en = request.getParameterNames();
	
	Cookie[] cookies = new Cookie[6];
	int cnt = 0;
	
	// 파라미터 이름 개수만큼 반복
	while(en.hasMoreElements()) {
		String paramName = (String)en.nextElement();
		
		out.print("<p>paramName : " + paramName + "</p>");
		
		// 쿠키 생성 Cookid(이름, 값)
		cookies[cnt] = new Cookie(
				"Shipping_" + paramName,
				URLEncoder.encode(request.getParameter(paramName),"UTF-8"));
		
		cookies[cnt].setMaxAge(24*60*60); //24시간
		response.addCookie(cookies[cnt]);
		
		cnt++;
	}// end while
		
	out.print("<p>------------</p>");
%>
<a href="/ch14/cookie02.jsp>" >[테스트]쿠키 생성 확인</a>

 

결과 화면5

 

 

cookie02.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<% //스크립틀릿
		Cookie[] cookies = request.getCookies();
		out.print("<p>현재 설정된 쿠키의 개수 : " + cookies.length + "<br />");
	%>
</body>
</html>

 

결과 화면6

 

 

=> 최종 processShippingInfo.jsp

processShippingInfo.jsp

<%@page import="java.net.URLEncoder"%>
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!--  
	요청URI : /processShippingInfo.jsp
	요청파라미터 : {cartId=sdfseef,name=개똥이,shippingDate=2024-04-22,
				country=대한민국,zipCode=12345,addressName=대전 중구 선화동123}
	요청방식 : post
-->
<%
	request.setCharacterEncoding("UTF-8");

	// 요청 파라미터 정보를 쿠키에 넣음
	// en{name, shippingDate, country, zipCode, addressName}
	Enumeration en = request.getParameterNames();
	
	Cookie[] cookies = new Cookie[6];
	int cnt = 0;
	
	// 파라미터 이름 개수만큼 반복
	while(en.hasMoreElements()) {
		String paramName = (String)en.nextElement();
		
		out.print("<p>paramName : " + paramName + "</p>");
		
		// 쿠키 생성 Cookid(이름, 값)
		cookies[cnt] = new Cookie(
				"Shipping_" + paramName,
				URLEncoder.encode(request.getParameter(paramName),"UTF-8"));
		
		cookies[cnt].setMaxAge(24*60*60); //24시간
		response.addCookie(cookies[cnt]);
		
		cnt++;
	}// end while
		
	out.print("<p>------------</p>");
	response.sendRedirect("/orderConfirmation.jsp");
%>
<a href="/ch14/cookie02.jsp" >[테스트]쿠키 생성 확인</a>

 

 

orderConfirmation.jsp

<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
   href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<title></title>
</head>
<body>
<%
	String Shipping_name = "";
	String Shipping_zipCode = "";
	String Shipping_country = "";
	String Shipping_addressName = "";
	String Shipping_shippingDate = "";
	String Shipping_cartId = "";
	
	Cookie[] cookies = request.getCookies();
	
	// 쿠키의 개수만큼 반복
	for(int i=0; i<cookies.length; i++){ //1(JSESSIONID) + 6(쿠키들)
		Cookie thisCookie = cookies[i];
		
		// 쿠키의 이름
		out.print("<p>" + thisCookie.getName() + "</p>");
		if(thisCookie.getName().equals("Shipping_zipCode")) {
			Shipping_zipCode 
				= URLDecoder.decode(thisCookie.getValue(),"UTF-8");
		}
		
		if(thisCookie.getName().equals("Shipping_cartId")) {
			Shipping_cartId 
				= URLDecoder.decode(thisCookie.getValue(),"UTF-8");
		}
		
		if(thisCookie.getName().equals("Shipping_name")) {
			Shipping_name 
				= URLDecoder.decode(thisCookie.getValue(),"UTF-8");
		}
		
		if(thisCookie.getName().equals("Shipping_shippingDate")) {
			Shipping_shippingDate
				= URLDecoder.decode(thisCookie.getValue(),"UTF-8");
		}
		
		if(thisCookie.getName().equals("Shipping_country")) {
			Shipping_country
				= URLDecoder.decode(thisCookie.getValue(),"UTF-8");
		}
		
		if(thisCookie.getName().equals("Shipping_addressName")) {
			Shipping_addressName
				= URLDecoder.decode(thisCookie.getValue(),"UTF-8");
		}
	}// end for
%>

	<%@ include file="/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>
		<!-- 고객 정보 시작 : cookie 사용 -->
		<div class="row justify-content-between">
			<strong>배송 주소</strong>
			성명 : <%=Shipping_name%><br />
			우편번호 : <%=Shipping_zipCode%><br />
			주소 : <%=Shipping_addressName%>&nbsp;<%=Shipping_country%>
		</div>
		<div class="col-4" align="right">
			<p>
				<em>배송일 : <%=Shipping_shippingDate%></em>
			</p>
		</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>
				<c:set var="cartlist" value="${sessionScope.cartlist}" />
				<c:forEach var="productVO" items="${cartlist}" varStatus="stat">
					<c:set var="sum" value="${sum +productVO.unitPrice*productVO.quantity}" />
					<tr>
						<td class="text-center"><em>${productVO.pname}</em></td>
						<td class="text-center">${productVO.quantity}</td>
						<td class="text-center">
							<fmt:formatNumber value="${productVO.unitPrice}" pattern="#,###" /> 원
						</td>
						<td class="text-center">
							<fmt:formatNumber value="${productVO.unitPrice*productVO.quantity}" pattern="#,###" /> 원
						</td>
					</tr>
				</c:forEach>
				<tr>
					<td></td>
					<td></td>
					<td class="text-right"><strong>총액</strong></td>
					<td class="text-center text-danger"><strong>
						<fmt:formatNumber value="${sum}" pattern="#,###" />
					</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>

	<%@ include file="/footer.jsp"%>

</body>
</html>

 

결과 화면7

 

 

 

주문 완료

 

 

thankCustomer.jsp

<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
	String Shipping_name = "";
	String Shipping_zipCode = "";
	String Shipping_country = "";
	String Shipping_addressName = "";
	String Shipping_shippingDate = "";
	String Shipping_cartId = "";
	
	Cookie[] cookies = request.getCookies();
	
	// 쿠키의 개수만큼 반복
	for(int i=0; i<cookies.length; i++){ //1(JSESSIONID) + 6(쿠키들)
		Cookie thisCookie = cookies[i];
		
		// 쿠키의 이름
		out.print("<p>" + thisCookie.getName() + "</p>");
		if(thisCookie.getName().equals("Shipping_zipCode")) {
			Shipping_zipCode 
				= URLDecoder.decode(thisCookie.getValue(),"UTF-8");
		}
		
		if(thisCookie.getName().equals("Shipping_cartId")) {
			Shipping_cartId 
				= URLDecoder.decode(thisCookie.getValue(),"UTF-8");
		}
		
		if(thisCookie.getName().equals("Shipping_name")) {
			Shipping_name 
				= URLDecoder.decode(thisCookie.getValue(),"UTF-8");
		}
		
		if(thisCookie.getName().equals("Shipping_shippingDate")) {
			Shipping_shippingDate
				= URLDecoder.decode(thisCookie.getValue(),"UTF-8");
		}
		
		if(thisCookie.getName().equals("Shipping_country")) {
			Shipping_country
				= URLDecoder.decode(thisCookie.getValue(),"UTF-8");
		}
		
		if(thisCookie.getName().equals("Shipping_addressName")) {
			Shipping_addressName
				= URLDecoder.decode(thisCookie.getValue(),"UTF-8");
		}
	}// end for
%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
   href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/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>
		<p>주문은 <%=Shipping_shippingDate%>에 배송될 예정입니다.</p>
		<p>주문번호 : <%=Shipping_cartId%></p>
	</div>
	<div class="container">
		<p>
			<a href="/products.jsp" class="btn btn-secondary">&laquo;상품 목록</a>
			<a href="/ch14/cookie02.jsp" class="btn btn-secondary">&laquo;쿠키정보 확인</a>
		</p>
	</div>

	<%@ include file="/footer.jsp"%>

<%
	session.removeAttribute("cartlist");
	
	//쿠키의 개수만큼 반복
	for(int i=0; i<cookies.length; i++){ //1(JSESSIONID) + 6(쿠키들)
		Cookie thisCookie = cookies[i];
		
		// 쿠키인 JSESSIONID는 없앨 수 없음
		if(!thisCookie.getName().equals("JSESSIONID")) {
			// 쿠키의 유효기간을 0으로 설정 -> 쿠키 정보 삭제
			thisCookie.setMaxAge(0);
			response.addCookie(thisCookie);
		}
	}// end for
%>
</body>
</html>

 

결과 화면8

 

결과 화면9 : /ch14/cookie02.jsp 를 탔을 때의 화면

 

 

 

 

주문 취소

 

 

checkOutCancelled.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
   href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/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>

	<!-- 장바구니를 비움 -->
	<%
		session.removeAttribute("cartlist"); 
	%>
	<div class="container">
		<h2 class="alert alert-danger">주문이 취소되었습니다.</h2>
	</div>
	<div class="container">
		<p><a href="/products.jsp" class="btn btn-secondary">&laquo;상품 목록</a></p>
	</div>

	<jsp:include page="/footer.jsp" />
</body>
</html>

 

결과 화면10

 

 

반응형

'스프링' 카테고리의 다른 글

[스프링] 23장 전자정부프레임워크 다운로드  (0) 2024.04.19
[스프링] 22.5장 과제  (0) 2024.04.18
[스프링] 21장 세션  (1) 2024.04.18
[스프링] 20장 과제  (0) 2024.04.17
[스프링] 19장 필터, 쇼핑몰 시스템7  (0) 2024.04.17
1 2 3 4 ··· 9