[ cartForm.jsp ]
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<% request.setCharacterEncoding("UTF-8"); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cart</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<link rel="stylesheet" href="/resources/css/cart.css">
</head>
<body>
<!-- 메뉴바 -->
<jsp:include page="../common/header.jsp" flush="false"/>
<div class="wrapper">
<div class="wrap">
<div class="content_area">
<div class="content_subject"><span>장바구니</span></div>
<!-- 장바구니 리스트 -->
<div class="content_middle_section"></div>
<!-- 장바구니 가격 합계 -->
<!-- cartInfo -->
<div class="content_totalCount_section">
<!-- 체크박스 전체 여부 -->
<div class="all_check_input_div">
<input type="checkbox" class="all_check_input input_size_20" checked="checked"><span class="all_chcek_span">전체선택</span>
</div>
<table class="subject_table">
<caption>표 제목 부분</caption>
<tbody>
<tr>
<th class="td_width_1"></th>
<th class="td_width_2"></th>
<th class="td_width_3">상품명</th>
<th class="td_width_4">금액</th>
<th class="td_width_4">수량</th>
<th class="td_width_4">합계</th>
<th class="td_width_4">삭제</th>
</tr>
</tbody>
</table>
<table class="cart_table">
<caption>표 내용 부분</caption>
<tbody>
<c:forEach items="${cartInfo}" var="cartInfo">
<tr>
<td class="td_width_1 cart_info_td">
<input type="checkbox" class="individual_cart_checkbox input_size_20" checked="checked">
<input type="hidden" class="individual_p_price_input" value="${cartInfo.p_price}">
<input type="hidden" class="individual_ci_number_input" value="${cartInfo.ci_number}">
<input type="hidden" class="individual_totalPrice_input" value="${cartInfo.p_price * cartInfo.ci_number}">
<input type="hidden" class="individual_point_input" value="${cartInfo.point}">
<input type="hidden" class="individual_totalPoint_input" value="${cartInfo.totalPoint}">
</td>
<td class="td_width_2"></td>
<td class="td_width_3">${cartInfo.p_name}</td>
<td class="td_width_4 price_td">
금액 : <fmt:formatNumber value="${cartInfo.p_price}" pattern="#,### 원" /><br>
마일리지 : <span class="green_color"><fmt:formatNumber value="${cartInfo.point}" pattern="#,###" /></span>
</td>
<td class="td_width_4 table_text_align_center">
<div class="table_text_align_center quantity_div">
<input type="text" value="${cartInfo.ci_number}" class="quantity_input">
<button class="quantity_btn plus_btn">+</button>
<button class="quantity_btn minus_btn">-</button>
</div>
<a class="quantity_modify_btn">변경</a>
</td>
<td class="td_width_4 table_text_align_center">
<fmt:formatNumber value="${cartInfo.p_price * cartInfo.ci_number}" pattern="#,### 원" />
</td>
<td class="td_width_4 table_text_align_center delete_btn"><button>삭제</button></td>
</tr>
</c:forEach>
</tbody>
</table>
<table class="list_table">
</table>
</div>
<!-- 가격 종합 -->
<div class="content_total_section">
<div class="total_wrap">
<table>
<tr>
<td>
<table>
<tr>
<td>총 상품 가격</td>
<td>
<span class="totalPrice_span"></span> 원
</td>
</tr>
<tr>
<td>배송비</td>
<td>
<span class="delivery_price"></span>원
</td>
</tr>
<tr>
<td>총 주문 상품수</td>
<td><span class="totalCount_span"></span>개</td>
</tr>
</table>
</td>
<td>
<table>
<tr>
<td></td>
<td></td>
</tr>
</table>
</td>
</tr>
</table>
<div class="boundary_div">구분선</div>
<table>
<tr>
<td>
<table>
<tbody>
<tr>
<td>
<strong>총 결제 예상 금액</strong>
</td>
<td>
<span class="finalTotalPrice_span"></span> 원
</td>
</tr>
</tbody>
</table>
</td>
<td>
<table>
<tbody>
<tr>
<td>
<strong>총 적립 예상 마일리지</strong>
</td>
<td>
<span class="totalPoint_span"></span> 원
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</div>
</div>
<!-- 구매 버튼 영역 -->
<div class="content_btn_section">
<a>주문하기</a>
</div>
</div>
</div>
</div>
<!-- 푸터영역 -->
<jsp:include page="../common/footer.jsp" flush="false"/>
</body>
<script>
$(document).ready(function(){
/* 종합 정보 섹션 정보 삽입 */
setTotalInfo();
})
/* 체크여부에따른 종합 정보 변화 */
// '종합 정보 섹션' 정보들 업데이트되도록 setTotalInfo() 메서드 호출
$(".individual_cart_checkbox").on("change", function(){
/* 총 주문 정보 세팅(배송비, 총 가격, 마일리지, 물품 수, 종류) */
setTotalInfo($(".cart_info_td"));
});
/* 체크박스 전체 선택 */
$(".all_check_input").on("click", function(){
/* 체크박스 체크/해제 */
if($(".all_check_input").prop("checked")){
$(".individual_cart_checkbox").attr("checked", true);
} else{
$(".individual_cart_checkbox").attr("checked", false);
}
/* 총 주문 정보 세팅(배송비, 총 가격, 마일리지, 물품 수, 종류) */
setTotalInfo($(".cart_info_td"));
});
/* 총 주문 정보 세팅(배송비, 총 가격, 마일리지, 물품 수, 종류) */
function setTotalInfo(){
let totalPrice = 0; // 총 가격
let totalCount = 0; // 총 개수
let totalPoint = 0; // 총 포인트 점수
let deliveryPrice = 0; // 배송비
let finalTotalPrice = 0; // 최종 가격(총 가격 + 배송비)
// element(<td> 객체)에 있는 체크박스('.individual_cart_checkbox' <input>)가
// checked 상태일 때 true이면 참이된다는 의미
$(".cart_info_td").each(function(index, element){
if($(element).find(".individual_cart_checkbox").is(":checked") === true) {
// 총 가격
totalPrice += parseInt($(element).find(".individual_totalPrice_input").val());
// 총 개수
totalCount += parseInt($(element).find(".individual_ci_number_input").val());
// 총 마일리지
totalPoint += parseInt($(element).find(".individual_totalPoint_input").val());
}
});
/* 배송비 결정 */
if(totalPrice >= 30000){
deliveryPrice = 0;
} else if(totalPrice == 0){
deliveryPrice = 0;
} else {
deliveryPrice = 3000;
}
/* 최종 가격 */
finalTotalPrice = totalPrice + deliveryPrice;
/* 값 삽입 */
// 총 가격
$(".totalPrice_span").text(totalPrice.toLocaleString());
// 총 갯수
$(".totalCount_span").text(totalCount);
// 총 마일리지
$(".totalPoint_span").text(totalPoint.toLocaleString());
// 배송비
$(".delivery_price").text(deliveryPrice);
// 최종 가격(총 가격 + 배송비)
$(".finalTotalPrice_span").text(finalTotalPrice.toLocaleString());
};
</script>
</html>
[ CartDTO.java ]
package com.daily.www.cart.dto;
import org.springframework.stereotype.Component;
import lombok.Data;
@Data
@Component("cartDTO")
public class CartDTO {
private int cartItem_id; // 장바구니 아이템 아이디(기본키)
private int id; // 회원 아이디(외래키)
private int cart_id; // 장바구니 아이디(외래키)
private int ci_number; // 상품 수량
private int product_id; // 상품 아이디(외래키)
private String p_name; // 상품명(외래키)
private int p_price; // 상품 금액(외래키)
private int point;
private int totalPoint;
public int getPoint() {
return point;
}
public int getTotalPoint() {
return totalPoint;
}
public void priceTotal() {
this.point = (int)(Math.floor(this.p_price*0.05));
this.totalPoint =this.point * this.ci_number;
}
}
[ CartController.java ]
package com.daily.www.cart.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.daily.www.cart.dto.CartDTO;
import com.daily.www.cart.service.CartService;
@Controller
@RequestMapping(value = "/cart/*")
public class CartController {
private static final Logger logger = LoggerFactory.getLogger(CartController.class);
@Autowired
private CartService cartService;
//-----------------------------------------------------------------------------------------------------------
// 장바구니 화면 불러오기
//-----------------------------------------------------------------------------------------------------------
@RequestMapping(value = "/cartForm", method = RequestMethod.GET)
public String cartForm(CartDTO cartDTO, String cart_id, Model model) {
logger.info("CartController 상품 등록 화면 불러오기.....");
cart_id = "1";
cartService.getCartList(cart_id);
model.addAttribute("cartInfo", cartService.getCartList(cart_id));
return "/cart/cartForm";
}
@PostMapping("/cart/add")
@ResponseBody
public String addCartPOST(CartDTO cartDTO) {
// 카트 등록
int result = cartService.addCart(cartDTO);
return result + "";
}
// @GetMapping("/cart/{cart_id}")
// public String cartPageGET(@PathVariable("cart_id") String cart_id, Model model) {
//
// model.addAttribute("cartInfo", cartService.getCartList(cart_id));
//
// return "/cart";
// }
// @Autowired
// private CartService cartService;
// //-----------------------------------------------------------------------------------------------------------
// // 로그인 여부 체크
// //-----------------------------------------------------------------------------------------------------------
// @PostMapping("/cart/add")
// @ResponseBody
// public String addCartPOST(CartDTO cartDTO, HttpServletRequest request) {
// // 로그인 체크
// HttpSession session = request.getSession();
// MemberVO mvo = (MemberVO)session.getAttribute("member");
// if(mvo == null) {
// return "5";
// }
//
// // 카트 등록
//
// int result = cartService.addCart(cartDTO);
//
// return result + "";
// }
}
[ CartService.java ]
package com.daily.www.cart.service;
import java.util.List;
import com.daily.www.cart.dto.CartDTO;
public interface CartService {
// -----------------------------------------------------------------
// 장바구니 추가
// -----------------------------------------------------------------
public int addCart(CartDTO cartDTO);
// -----------------------------------------------------------------
// 장바구니 정보 리스트
// -----------------------------------------------------------------
public List<CartDTO> getCartList(String cart_id);
}
[ CartServiceImpl.java ]
package com.daily.www.cart.service;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import com.daily.www.cart.dao.CartDAO;
import com.daily.www.cart.dto.CartDTO;
@Service
public class CartServiceImpl implements CartService {
@Inject
private CartDAO cartDAO;
// -----------------------------------------------------------------
// 장바구니 추가
// -----------------------------------------------------------------
@Override
public int addCart(CartDTO cartDTO) {
// 등록하고자 하는 데이터가 이미 DB에 존재하는지 확인
CartDTO checkCart = cartDAO.checkCart(cartDTO);
if(checkCart != null) {
return 2;
}
// 장바구니 등록 & 에러 시 0 반환
try {
return cartDAO.addCart(cartDTO);
} catch(Exception e) {
return 0;
}
} // End - 장바구니 추가
// -----------------------------------------------------------------
// 장바구니 리스트
// -----------------------------------------------------------------
@Override
public List<CartDTO> getCartList(String cart_id) {
List<CartDTO> cartDTO = cartDAO.getCart(cart_id);
for(CartDTO dto : cartDTO) {
dto.priceTotal();
}
return cartDTO;
}
}
[ CartDAO.java ]
package com.daily.www.cart.dao;
import java.util.List;
import com.daily.www.cart.dto.CartDTO;
public interface CartDAO {
//-----------------------------------------------------------------------------------------------------------
// 카트 추가
//-----------------------------------------------------------------------------------------------------------
public int addCart(CartDTO cartDTO) throws Exception;
//-----------------------------------------------------------------------------------------------------------
// 카트 삭제
//-----------------------------------------------------------------------------------------------------------
public int deleteCart(int cartItem_id);
//-----------------------------------------------------------------------------------------------------------
// 카트 수량 수정
//-----------------------------------------------------------------------------------------------------------
public int modifyCount(CartDTO cartDTO);
//-----------------------------------------------------------------------------------------------------------
// 카트 목록
//-----------------------------------------------------------------------------------------------------------
public List<CartDTO> getCart(String cart_id);
//-----------------------------------------------------------------------------------------------------------
// 카트 확인
//-----------------------------------------------------------------------------------------------------------
public CartDTO checkCart(CartDTO cartDTO);
}
[ CartDAOImpl.java ]
package com.daily.www.cart.dao;
import java.util.List;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import com.daily.www.cart.dto.CartDTO;
import com.daily.www.product.dto.ProductDTO;
//------------------------------------------------------------------------
// public class CartDAOImpl implements CartDAO
//------------------------------------------------------------------------
@Repository
public class CartDAOImpl implements CartDAO {
private static final Logger logger = LoggerFactory.getLogger(CartDAOImpl.class);
@Inject
private SqlSession sqlSession;
private static String namespace = "com.daily.www.cart";
//------------------------------------------------------------------------
// 장바구니에 추가
//------------------------------------------------------------------------
@Override
public int addCart(CartDTO cartDTO) throws Exception {
logger.info("CartDAOImpl 장바구니에 추가 처리 ==> " + cartDTO);
return sqlSession.insert(namespace + ".addCart", cartDTO);
}
@Override
public int deleteCart(int cartItem_id) {
return 0;
}
@Override
public int modifyCount(CartDTO cartDTO) {
return 0;
}
//------------------------------------------------------------------------
// 장바구니 리스트 불러오기
//------------------------------------------------------------------------
@Override
public List<CartDTO> getCart(String cart_id) {
logger.info("CartDAOImpl cartList() 장바구니 목록 가져오기.....");
List<CartDTO> cartList = sqlSession.selectList(namespace + ".cartAll", cart_id);
logger.info("CartDAOImpl cartList() Data ==> " + cartList);
return cartList;
}
@Override
public CartDTO checkCart(CartDTO cartDTO) {
return null;
}
}
[ cartMapper.xml ]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.daily.www.cart">
<!-- 카트 추가 -->
<insert id="addCart" parameterType="com.daily.www.cart.dto.CartDTO">
<![CDATA[
INSERT INTO cartItem (ci_number, cartItem_id, product_id, cart_id)
VALUES (#{ci_number}, #{cartItem_id}, #{product_id}, #{cart_id})
]]>
</insert>
<!-- 카트 삭제 -->
<delete id="deleteCart">
<![CDATA[
DELETE
FROM cartItem
WHERE cartItem_id = #{cartItem_id}
]]>
</delete>
<!-- 카트 수량 수정 -->
<update id="modifyCount">
<![CDATA[
UPDATE cartItem
SET ci_number = #{ci_number}
WHERE cartItem_id = #{cartItem_id}
]]>
</update>
<!-- 카트 목록 -->
<select id="cartAll" resultType="com.daily.www.cart.dto.CartDTO">
<![CDATA[
SELECT a.cartItem_id, a.cart_id, a.product_id, a.ci_number
,b.p_name, b.p_price
FROM cartItem a LEFT OUTER JOIN product b
ON a.product_id = b.product_id
WHERE 1=1 AND cart_id = #{cart_id}
]]>
</select>
<!-- 카트 확인 -->
<select id="checkCart" resultType="com.daily.www.cart.dto.CartDTO">
<![CDATA[
SELECT *
FROM cartItem
WHERE cart_id = #{cart_id}
AND prodcut_id = #{product_id}
]]>
</select>
</mapper>
728x90
반응형
'프로그래밍 언어 > JSP' 카테고리의 다른 글
JSP_22-12-14_[쇼핑몰 만들기_장바구니 이미지 나열] (0) | 2022.12.14 |
---|---|
JSP_22-12-08_[ 쇼핑몰 장바구니 ]_소스 코드 정리 (0) | 2022.12.08 |
JSP_22-11-28_[상품 이미지 업로드] (0) | 2022.11.28 |
JSP_22-11-22_상품 등록[2] (0) | 2022.11.24 |