메뉴 상단 공통 출력 장바구니 목록 보기
package net.macaronics.web.controll.common; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import net.macaronics.web.dao.CartDAO; import net.macaronics.web.dto.CartVO; import net.macaronics.web.dto.MemberVO; public class CommonList { final static Logger logger = LogManager.getLogger(CommonList.class); public static void getCommon(HttpServletRequest request) { HttpSession session = ((HttpServletRequest) request).getSession(); MemberVO loginUser = (MemberVO) session.getAttribute("loginUser"); if (loginUser != null) { CartDAO cartDAO = CartDAO.getInstance(); List<CartVO> cartList = cartDAO.listCart(loginUser.getId()); int totalPrice = 0; for (CartVO cartVO : cartList) { totalPrice += cartVO.getPrice2() * cartVO.getQuantity(); } request.setAttribute("cartList", cartList); request.setAttribute("totalPrice", totalPrice); } } }
장바구니 담기
CartInsertAction
package net.macaronics.web.controll; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.macaronics.web.controll.action.Action; import net.macaronics.web.dao.CartDAO; import net.macaronics.web.dto.CartVO; import net.macaronics.web.dto.MemberVO; public class CartInsertAction implements Action { @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = "MacaronicsServlet?command=product_detail&pseq="; HttpSession session = request.getSession(); MemberVO loginUser = (MemberVO) session.getAttribute("loginUser"); if (loginUser == null) { url = "MacaronicsServlet?command=login_form"; } else { // 장바구니에 등록하기 CartVO cartVO = new CartVO(); cartVO.setId(loginUser.getId()); int pseq=Integer.parseInt(request.getParameter("pseq")); cartVO.setPseq(pseq); cartVO.setQuantity(Integer.parseInt(request.getParameter("quantity"))); CartDAO cartDAO = CartDAO.getInstance(); cartDAO.insertCart(cartVO); url += pseq; } response.sendRedirect(url); } }
CartInsertAjax
package net.macaronics.web.controll; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.spi.LoggerFactory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import net.macaronics.web.controll.action.Action; import net.macaronics.web.dao.CartDAO; import net.macaronics.web.dto.CartVO; import net.macaronics.web.dto.MemberVO; public class CartInsertAjax implements Action{ private static final Logger logger =LogManager.getLogger(CartInsertAjax.class); @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=utf-8"); HttpSession session =request.getSession(); MemberVO loginUser=(MemberVO)session.getAttribute("loginUser"); PrintWriter out =response.getWriter(); if(loginUser==null){ out.println("로그인을 먼저 하세요."); }else{ //장바구니에 등록하기 CartVO cartVO=new CartVO(); cartVO.setId(loginUser.getId()); cartVO.setPseq(Integer.parseInt(request.getParameter("pseq"))); cartVO.setQuantity(Integer.parseInt(request.getParameter("quantity"))); CartDAO cartDAO=CartDAO.getInstance(); cartDAO.insertCart(cartVO); out.println("success"); } } }
장바구니 목록 보기
CartListAction
package net.macaronics.web.controll; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.macaronics.web.controll.action.Action; import net.macaronics.web.controll.common.CommonList; import net.macaronics.web.dao.CartDAO; import net.macaronics.web.dto.CartVO; import net.macaronics.web.dto.MemberVO; public class CartListAction implements Action { //장바구니 목록 보기 @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url="mypage/cartList.jsp"; HttpSession session=request.getSession(); MemberVO loginUser=(MemberVO)session.getAttribute("loginUser"); if(loginUser==null){ url="MacaronicsServlet?command=login_form"; }else{ //공통 리스트 장바구니 목록 //MacaronicsServlet 존재 } request.getRequestDispatcher(url).forward(request, response); } }
장바구니 삭제하기
CartDeleteAction
package net.macaronics.web.controll; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import net.macaronics.web.controll.action.Action; import net.macaronics.web.dao.CartDAO; import net.macaronics.web.dto.MemberVO; public class CartDeleteAction implements Action { final static Logger logger = LogManager.getLogger(CartDeleteAction.class); @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = "MacaronicsServlet?command=cart_list"; String[] cseqArr = request.getParameterValues("cseq"); MemberVO member = (MemberVO) request.getSession().getAttribute("loginUser"); try { for (String cseq : cseqArr) { logger.info(cseq); CartDAO dao = CartDAO.getInstance(); dao.deleteCart(Integer.parseInt(cseq), member.getId()); } response.sendRedirect(url); } catch (Exception e) { e.printStackTrace(); response.sendRedirect(url); } } }
CartDeleteAjaxAction
package net.macaronics.web.controll; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import net.macaronics.web.controll.action.Action; import net.macaronics.web.dao.CartDAO; import net.macaronics.web.dto.MemberVO; public class CartDeleteAjaxAction implements Action { final static Logger logger = LogManager.getLogger(CartDeleteAjaxAction.class); @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String cseq = request.getParameter("cseq"); MemberVO member = (MemberVO) request.getSession().getAttribute("loginUser"); try { logger.info(cseq); CartDAO dao = CartDAO.getInstance(); dao.deleteCart(Integer.parseInt(cseq), member.getId()); out.println("success"); } catch (Exception e) { e.printStackTrace(); out.print("failed"); } } }
Url 매핑
ActionFactory
package net.macaronics.web.controll.factory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import net.macaronics.web.controll.CartDeleteAction; import net.macaronics.web.controll.CartDeleteAjaxAction; import net.macaronics.web.controll.CartInsertAction; import net.macaronics.web.controll.CartInsertAjax; import net.macaronics.web.controll.CartListAction; import net.macaronics.web.controll.IndexAction; import net.macaronics.web.controll.JoinFormAction; import net.macaronics.web.controll.LogOutAction; import net.macaronics.web.controll.LoginFormAction; import net.macaronics.web.controll.ProductDetailAction; import net.macaronics.web.controll.ProductKindAction; import net.macaronics.web.controll.action.Action; public class ActionFactory { final Logger logger =LogManager.getLogger(ActionFactory.class); //싱글톤설정 private static ActionFactory instance; private ActionFactory(){ super(); } public static ActionFactory getInstance(){ if(instance==null){ instance=new ActionFactory(); } return instance; } //command 에서 넘어온 파라미터 값이 존재하면 실행 //즉 ,존재하면 url 만 실행된다. public Action getAction(String command){ Action action=null; logger.info("ActionFactory : {} ", command); if(command.equals("index")) action=new IndexAction(); else if(command.equals("product_detail")) action=new ProductDetailAction();//상품 상세보기 else if(command.equals("category")) action=new ProductKindAction(); //상품종류별 보기 else if(command.equals("join_form"))action=new JoinFormAction(); //회워가입 else if(command.equals("login_form"))action=new LoginFormAction(); //로그인 else if(command.equals("logout")) action=new LogOutAction(); //로그아웃 else if(command.equals("cart_insert"))action=new CartInsertAction(); //장바구니에 담기 else if(command.equals("cart_list")) action=new CartListAction(); //장바구니 목록 else if(command.equals("cart_delete")) action=new CartDeleteAction(); //장바구니 삭제 else if(command.equals("cart_ajax")) action=new CartInsertAjax(); //장바구니 ajax 담기 else if(command.equals("cart_delete_ajax")) action=new CartDeleteAjaxAction(); //장바구니 ajax 삭제 return action; } }
DAO
CartDAO
package net.macaronics.web.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import config.MybatisService; import net.macaronics.web.dto.CartVO; public class CartDAO { private final static Logger logger =LogManager.getLogger(CartDAO.class); //Mybatis private SqlSession sqlSession; // CartDAO 싱글톤 객체 만들기 private static CartDAO instance =new CartDAO(); private CartDAO(){ } public static CartDAO getInstance(){ if(instance==null){ instance=new CartDAO(); } return instance; } //장바구니 담기 public void insertCart(CartVO cartVO){ try{ sqlSession=MybatisService.getFactory().openSession(); sqlSession.insert("cart.insertCart", cartVO); }catch(Exception e){ e.printStackTrace(); }finally{ sqlSession.commit(); MybatisService.sessionClose(sqlSession); } } //장바구니 목록 public List<CartVO> listCart(String userid){ List<CartVO> cartList=new ArrayList<>(); try{ sqlSession=MybatisService.getFactory().openSession(); cartList=sqlSession.selectList("cart.listCart", userid); }catch(Exception e){ e.printStackTrace(); }finally{ sqlSession.commit(); MybatisService.sessionClose(sqlSession); } return cartList; } //장바구니 삭제 public void deleteCart(int cseq, String id){ try{ sqlSession=MybatisService.getFactory().openSession(); Map<String, Object> map=new HashMap<>(); map.put("cseq", cseq); map.put("id", id); sqlSession.delete("cart.deleteCart", map); }catch(Exception e){ e.printStackTrace(); }finally{ sqlSession.commit(); MybatisService.sessionClose(sqlSession); } } }
DTO
CartVO
public class CartVO { private int cseq; //장바구니 번호 private String id; //회원아이디 private int pseq; //상품번호 private String mname; //회원이름 private String pname; //상품이름 private int quantity; //수량 private int price2; //가격 private String image; private Timestamp indate; setter, getter
Mybatis
cart.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="cart"> <!-- id="태그의 식별자" resultType="sql 명령어의 리턴타입(레코드의 자료형)" 샵{변수} => 입력매개변수 --> <insert id="insertCart"> insert into tbl_cart(cseq, id, pseq, quantity) values( cart_seq.nextval, #{id} , #{pseq} , #{quantity}) </insert> <select id="listCart" resultType="net.macaronics.web.dto.CartVO"> select * from CART_VIEW where id=#{id} order by cseq desc </select> <delete id="deleteCart"> delete tbl_cart where cseq=#{cseq} and id=#{id} </delete> </mapper>
SQL
create or replace view cart_view as select o.cseq, o.id, o.pseq, m.name mname, p.name pname, o.quantity, o.indate, p.price2, o.result from tbl_cart o, tbl_member m, tbl_product p where o.id = m.id and o.pseq = p.pseq and result='1'
View
cartList.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" %> <!DOCTYPE html> <html> <head> <jsp:include page="../include/Header.jsp" /> </head> <body> <jsp:include page="../include/HeaderMenu.jsp" /> <!-- catg header banner section --> <section id="aa-catg-head-banner"> <img src="/dailyShop/img/slider/4.jpg" alt="fashion img" height="300" style="margin-left: auto; margin-right: auto; display: block;"> <div class="aa-catg-head-banner-area"> <div class="container"> </div> </div> </section> <!-- / catg header banner section --> <!-- Cart view section --> <section id="cart-view"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="cart-view-area"> <div class="cart-view-table"> <form action="" name="form1"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>삭제</th> <th>이미지</th> <th>상품</th> <th>가격</th> <th>수량</th> <th>합계</th> </tr> </thead> <tbody> <c:choose> <c:when test="${cartList.size() ==0 }"> <tr> <td colspan="6">장바구니가 비었습니다.</td> </tr> </c:when> <c:otherwise> <c:forEach items="${cartList }" var="cartVO"> <tr> <td> <a class="remove" href="#" onclick="go_cart_delete(${cartVO.cseq})"><fa class="fa fa-close"></fa></a> <input type="hidden" name="cseq" value="${cartVO.cseq}"> </td> <td><a href="MacaronicsServlet?command=product_detail&pseq=${cartVO.pseq}"><img src="images/${cartVO.image}" alt="img"></a></td> <td><a class="aa-cart-title" href="MacaronicsServlet?command=product_detail&pseq=${cartVO.pseq}">${cartVO.pname}</a></td> <td><fmt:formatNumber value="${cartVO.price2}" type="currency" /></td> <td><input class="aa-cart-quantity" type="number" value="${ cartVO.quantity}" min="1" max="100" readonly="readonly"></td> <td><fmt:formatNumber value="${cartVO.price2*cartVO.quantity }" type="currency" /> </td> </tr> </c:forEach> </c:otherwise> </c:choose> </tbody> </table> <input type="hidden" value="cart_delete" name="command"> </div> </form> <c:if test="${cartList.size() !=0 }"> <!-- Cart Total view --> <div class="cart-view-total"> <h4 style="text-align: center;">장바구니 합계</h4> <table class="aa-totals-table"> <tbody> <tr> <th>배송비(3만원 이상 무료)</th> <td><fmt:formatNumber type="currency" value="${totalPrice >30000 ? 0 :3000 }" /></td> </tr> <tr> <th>합계</th> <td><fmt:formatNumber value="${totalPrice > 30000 ? totalPrice: totalPrice+3000 }" type="currency" /></td> </tr> </tbody> </table> <a href="#" class="aa-cart-view-btn">주문하기</a> <a href="MacaronicsServlet?command=index" class="aa-cart-view-btn">쇼핑 계속하기</a> <a href="#" onclick="go_cart_all_delete()" class="btn btn-danger">장바구니 비우기</a> </div> </c:if> </div> </div> </div> </div> </div> </section> <!-- / Cart view section --> <jsp:include page="../include/Footer.jsp" />>
javascript
<script> //장바구니 에 담기 function go_cart(){ var loginUser='${sessionScope.loginUser}'; if(loginUser==null || loginUser==''){ alert("로그인을 먼저 하세요."); return; } if(document.formm.quantity.value==""){ alert("수량을 입력하여 주세요."); document.formm.quantity.focus(); }else{ $("input[name=command]").val("cart_insert"); document.formm.submit(); } } $(function(){ $(".cart-ajax").click(function(event){ event.preventDefault(); pseq=$(this).attr("data-pseq"); $.ajax({ url:"MacaronicsServlet?command=cart_ajax", type:"post", dataType:"text", data : { pseq:pseq, quantity:1 }, success:function(result){ if($.trim(result)=='success'){ if(confirm("장바구니에 담았습니다. 장바구니로 이동하시겠습니까?")){ location.href="/MacaronicsServlet?command=cart_list"; } }else{ alert($.trim(result)); } } }); }); }); function go_cart_delete(cseq){ if(confirm("정말 삭제하시겠습니까?")){ location.href="MacaronicsServlet?command=cart_delete&cseq="+cseq; } } function go_cart_all_delete(){ if(confirm("정말 삭제하시겠습니까?")){ document.form1.submit(); } } function go_cart_ajax_delete(cseq){ if(confirm("정말 삭제하시겠습니까?")){ $.ajax({ url:"MacaronicsServlet?command=cart_delete_ajax", type:"post", data:{cseq:cseq}, success:function(result){ if($.trim(result)=='success'){ alert("삭제 했습니다.") location.reload(); } } }); } } </script>
제작 : macaronics.net - Developer Jun Ho Choi
소스 : https://github.com/braverokmc79/jsp_sin
${request.getContextPath() } 처리를 안한 부분이 있으므로
루트 설정( http://macaronics.net/index.php/m01/jsp/view/1352) 및 server.xml 에서 DB 컨넥션 설정은 필수 설정이다.
댓글 ( 4)
댓글 남기기