[구현] 주문

서현서현·2022년 5월 30일
0

서블릿 & JSP

목록 보기
26/26

구조

SqlMap

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
    "http://ibatis.apache.org/dtd/sql-map-2.dtd">
    
<sqlMap namespace="orders">


	<resultMap class="gameVO" id="GameIdMap">
		<result property="game_id" column="game_id"/>
	</resultMap>
	
	<!-- 멤버 아이디를 파라미터로 갖고 그 멤버가 장바구니에 담은 모든 게임 아이디를 가져옴 -->
	<select id="getCartGameId" parameterClass="String" resultMap="GameIdMap">
		select b.game_id
		from cart a
		inner join cart_game b
		on(a.CART_NO = b.CART_NO)
		where a.mem_id = #memId#
	</select>

	<!-- 이제 장바구니에 있는 게임들의 정보둘을 가져오자 -->
  	<resultMap class="gameVO" id="GameInfo">
		<result property="game_id" column="game_id"/>
		<result property="game_name" column="game_name"/>
		<result property="game_price" column="game_price"/>
		<result property="game_img" column="game_img"/>
		<result property="age" column="age"/>
	</resultMap>
	<select id="getGameInfo" parameterClass="String" resultMap="GameInfo">
		select game_id, game_name, game_price, game_img, age
		from game
		where game_id= #gameId#
	</select>
	
	
  	<resultMap class="MemberVO" id="MemInfo">
		<result property="mem_id" column="mem_id"/>
		<result property="mem_name" column="mem_name"/>
		<result property="mem_mail" column="mem_mail"/>
		<result property="mem_ph" column="mem_ph"/>
	</resultMap>
	<!-- memId를 이용해서 name, email, phone 찾아주기 -->
	<select id="getMemInfo" parameterClass="String" resultMap="MemInfo">
		select mem_id, mem_name, mem_mail, mem_ph
		from member
		where mem_id= #memId#
	</select>


	<!-- 특정 사용자가 구매 완료한 게임의game_id -->
	<select id="getOrderedGameId" parameterClass="String" resultClass="String">
		select game_id
		from cart_game
		where cart_no in (
		select b.cart_no
		from CART a
		inner join orders b
		on (a.CART_NO = b.CART_NO)
		where a.mem_id= #memId#)
	</select>
	
	
	<!-- 구매 완료하고 나서 그 구매정보를 ORDER테이블에 넣자! -->
	<insert id="insertOrders" parameterClass="String">
		insert into orders values(fn_order_no, #cartNo#, sysdate)
	</insert>
	
	<!-- gameId가 주어질때 카트번호 -->
	<select id="getCartNo" parameterClass="java.util.Map" resultClass="String">
		select a.cart_no
		from cart_game a
		inner join cart b
		on (a.cart_no = b.cart_no)
		where a.game_id= #gameId# and b.mem_id= #memId#
	</select>
	
	
	<select id="orderExist" parameterClass="String" resultClass="String">
		select cart_no
		from orders
		where cart_no = #cartNo#
	</select>
	
	<resultMap class="OrderVO" id="orderMap">
		<result property="orderNo" column="order_no"/>
		<result property="cartNo" column="cart_no"/>
		<result property="orderDt" column="order_dt"/>
		<result property="gameId" column="game_id"/>
		<result property="gameName" column="game_name"/>
		<result property="gamePrice" column="game_price"/>
		<result property="memId" column="mem_id"/>
	</resultMap>
	
	<select id="getOrderList" parameterClass="String" resultMap="orderMap">
		select a.cart_no, b.order_no, c.mem_id, g.game_id, g.game_price, g.game_name, b.order_dt
		from cart a, orders b, member c, cart_game d, (select e.cart_no, f.game_id, f.game_price, f.game_name
		                                                from cart_game e, game f
		                                                where e.game_id = f.game_id) g
		where a.cart_no = d.cart_no
		and a.cart_no = b.cart_no
		and a.mem_id = c.mem_id
		and a.cart_no = g.cart_no
		and c.mem_id = #memId#
	</select>
</sqlMap>

OrderVO

package orders.vo;

public class OrderVO {
	private String orderNo;
	private String cartNo;
	private String orderDt;
	private String gameId;
	private String gameName;
	private String gamePrice;
	private String memId;
	
	public String getMemId() {
		return memId;
	}

	public void setMemId(String memId) {
		this.memId = memId;
	}

	public String getGameId() {
		return gameId;
	}

	public void setGameId(String gameId) {
		this.gameId = gameId;
	}

	public String getGameName() {
		return gameName;
	}

	public void setGameName(String gameName) {
		this.gameName = gameName;
	}

	public String getGamePrice() {
		return gamePrice;
	}

	public void setGamePrice(String gamePrice) {
		this.gamePrice = gamePrice;
	}

	public String getOrderNo() {
		return orderNo;
	}
	
	public void setOrderNo(String orderNo) {
		this.orderNo = orderNo;
	}
	
	public String getOrderDt() {
		return orderDt;
	}
	
	public void setOrderDt(String orderDt) {
		this.orderDt = orderDt;
	}

	public String getCartNo() {
		return cartNo;
	}

	public void setCartNo(String cartNo) {
		this.cartNo = cartNo;
	}

	
}

OrderDAO

IOrderDao

package orders.dao;

import java.util.List;

import games.game.vo.GameVO;
import members.member.vo.MemberVO;
import orders.vo.OrderVO;

public interface IOrderDao {
	
	// 주문창
	public List<String> getOrderedGameId(String memId);
	public List<GameVO> getGamesOfMyCart(String memId);
	public GameVO getGamesInfo(String gameId);
	public String getCartNo(String gameId, String memId);
	
	// 카카오페이
	public MemberVO MemInfo(String memId);

	public void insertOrder(String cartNo);
	
	public String orderExist(String cartNo);
	
	// 주문내역
	public List<OrderVO> getOrderList(String memId);
	
	
}

OrderDaoImpl

package orders.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ibatis.sqlmap.client.SqlMapClient;

import config.SqlMapClientFactory;
import games.game.vo.GameVO;
import members.member.vo.MemberVO;
import orders.vo.OrderVO;

public class OrderDaoImpl implements IOrderDao {

	private static IOrderDao dao;
	private SqlMapClient smc;

	private OrderDaoImpl() {
		smc = SqlMapClientFactory.getInstance();
	}

	public static IOrderDao getInstance() {
		if (dao == null) {
			dao = new OrderDaoImpl();
		}
		return dao;
	}

	@Override
	public List<GameVO> getGamesOfMyCart(String memId) {

		List<GameVO> gamesOfCartList = new ArrayList<GameVO>();

		try {

			gamesOfCartList = (List<GameVO>) smc.queryForList("orders.getCartGameId", memId);

		} catch (SQLException ex) {
			ex.printStackTrace();
			throw new RuntimeException("회원의 장바구니에 있는 모든 게임 조회중 예외 발생!", ex);
		}

		return gamesOfCartList;
	}

	// gameId는 당연히 여러개임... 그 Id가 모두 들어가서 각 Id에 해당하는 vo들의 리스트가 만들어져야...
	// 컨트롤러에서 반복문 돌려도 되나? => 매번 새 리스트 만드는거니까 안됨..
	// 그럼 여기서 돌려보자 한번...

	// gameId는 당연히 여러개임... 그 Id가 모두 들어가서 각 Id에 해당하는 vo들의 리스트가 만들어져야...
	// 컨트롤러에서 반복문 돌려도 되나? => 매번 새 리스트 만드는거니까 안됨..
	// 그럼 여기서 돌려보자 한번...
	@Override
	public GameVO getGamesInfo(String gameId) {

		GameVO vo = new GameVO();

		try {
				vo = (GameVO) smc.queryForObject("orders.getGameInfo", gameId);

		} catch (SQLException ex) {
			ex.printStackTrace();
			throw new RuntimeException("회원이 구매하려는 게임의 기타정보들을 불러오던 중 예외 발생!", ex);
		}
		return vo;
	}

	@Override
	public MemberVO MemInfo(String memId) {

		MemberVO vo = new MemberVO();

		try {

			vo = (MemberVO) smc.queryForObject("orders.getMemInfo", memId);

		} catch (SQLException ex) {
			ex.printStackTrace();
			throw new RuntimeException("결제를 위한 회원 개인정보 조회중 예외 발생!", ex);
		}

		return vo;
	}

	@Override
	public List<String> getOrderedGameId(String memId) {
		List<String> OrderedGameIdList = new ArrayList<String>();

		try {

			OrderedGameIdList = (List<String>) smc.queryForList("orders.getOrderedGameId", memId);

		} catch (SQLException ex) {
			ex.printStackTrace();
			throw new RuntimeException("회원이 구매완료한 게임아이디 조회중 예외 발생!", ex);
		}

		return OrderedGameIdList;
	}

	@Override
	public void insertOrder(String cartNo) {
		// TODO Auto-generated method stub
		try {
			smc.update("orders.insertOrders", cartNo);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}



	@Override
	public String getCartNo(String gameId, String memId) {
		String cartNo = null;
		Map map = new HashMap();
		map.put("gameId", gameId);
		map.put("memId", memId);
		try {
			System.out.println("null나와라 뚝딱   :   "+cartNo);
			cartNo = (String) smc.queryForObject("orders.getCartNo",map);
			System.out.println("orders.getCartNo 쿼리 제대로 실행되니?????? => "+cartNo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cartNo;
	}
	
	
	@Override
	public String orderExist(String cartNo) {
		String orderExist = "";
		
		try {
					
			orderExist = (String) smc.queryForObject("orders.orderExist",cartNo);

				} catch (SQLException ex) {
					ex.printStackTrace();
					throw new RuntimeException("orderExist 조회중 예외!",ex);
				}
		
		return orderExist;
	}

	@Override
	public List<OrderVO> getOrderList(String memId) {
		List<OrderVO> orderList = new ArrayList<OrderVO>();
		
		try {
			orderList = (List<OrderVO>) smc.queryForList("orders.getOrderList", memId);
		} catch(SQLException ex) {
			ex.printStackTrace();
			throw new RuntimeException("전체 주문사항 조회 중 예외발생!", ex);
		}
		return orderList;
	}

}

OrderService

IOrderService

package orders.service;

import java.util.List;

import games.game.vo.GameVO;
import members.member.vo.MemberVO;
import orders.vo.OrderVO;

public interface IOrderService {
	// 주문창
	public List<String> getOrderedGameId(String memId);
	public List<GameVO> getGamesOfMyCart(String memId);
	public GameVO getGamesInfo(String gameId);
	public String getCartNo(String gameId, String memId);
	
	// 카카오페이
	public MemberVO MemInfo(String memId);
	
	
	//
	public void insertOrder(String cartNo);
	public String orderExist(String cartNo);
	
	// 주문내역
	public List<OrderVO> getOrderList(String memId);
}

OrderServiceImpl

package orders.service;

import java.util.List;

import games.game.vo.GameVO;
import members.member.vo.MemberVO;
import orders.dao.IOrderDao;
import orders.dao.OrderDaoImpl;
import orders.vo.OrderVO;

public class OrderServiceImpl implements IOrderService {

	private static IOrderService service;
	private IOrderDao dao;

	private OrderServiceImpl() {
		dao = OrderDaoImpl.getInstance();
	}

	public static IOrderService getInstance() {
		if (service == null) {
			service = new OrderServiceImpl();
		}
		return service;
	}

	@Override
	public List<GameVO> getGamesOfMyCart(String memId) {
		return dao.getGamesOfMyCart(memId);
	}

	@Override
	public GameVO getGamesInfo(String gameId) {
		return dao.getGamesInfo(gameId);
	}

	@Override
	public MemberVO MemInfo(String memId) {
		return dao.MemInfo(memId);
	}

	@Override
	public List<String> getOrderedGameId(String memId) {
		return dao.getOrderedGameId(memId);
	}

	@Override
	public void insertOrder(String cartNo) {
		// TODO Auto-generated method stub
		dao.insertOrder(cartNo);
	}


	@Override
	public String getCartNo(String gameId, String memId) {
		return dao.getCartNo(gameId, memId);
	}
	
	@Override
	public String orderExist(String cartNo) {
		return dao.orderExist(cartNo);
	}

	@Override
	public List<OrderVO> getOrderList(String memId) {
		return dao.getOrderList(memId);
	}

}

OrderController

ListOrderController

package orders.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import members.member.vo.MemberVO;
import orders.service.IOrderService;
import orders.service.OrderServiceImpl;
import orders.vo.OrderVO;


@MultipartConfig(fileSizeThreshold = 1024 * 1024 *1000, maxFileSize = 1024 * 1024 * 1000, maxRequestSize = 1024 * 1024 * 1000)
@WebServlet("/listOrder.do")
public class ListOrderController extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		IOrderService orderService = OrderServiceImpl.getInstance();
		
		HttpSession session = req.getSession();
		MemberVO member = (MemberVO) session.getAttribute("loginMember");
		List<OrderVO> orderList = orderService.getOrderList(member.getMem_id());
		
		req.setAttribute("orderList", orderList);
		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");
		RequestDispatcher rd = req.getRequestDispatcher("main/accountOrder2.jsp");
		rd.forward(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

OrderController

package orders.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import games.game.vo.FreeGameVO;
import games.game.vo.GameVO;
import members.member.vo.MemberVO;
import orders.cart.service.CartServiceImpl;
import orders.cart.service.ICartService;
import orders.cart.vo.CartVO;
import orders.service.IOrderService;
import orders.service.OrderServiceImpl;
import wishList.service.IWishListService;
import wishList.service.WishListServiceImpl;

@WebServlet("/orderController.do")
public class OrderController extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		// 게임상세에서 memId와 gameId를 포함하여 들어올수도 있고, 장바구니에서 memId만 갖고 들어올수도 있음
		// 구분은 파라미터 존재여부로 나누려고 한다. gameId를 가지고 있는가>
		List<String> gamesIdList = new ArrayList<String>(); 
		List<GameVO> gameInfoList = new ArrayList<GameVO>(); 
		List<String> cartNoList = new ArrayList<String>();
		IOrderService orderSerice = OrderServiceImpl.getInstance();
		String msg="";
		System.out.println("상세페이지에서 주문하기 눌러 주문창 진입");
		// 이미 결제된 항목도 결제창으로 넘어가져버림... 검사해서 분기문으로 처리하자!!!!!
		 if(req.getParameterMap().containsKey("gameId")) { 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// 1 상세페이지에서 구매할때
			 	
				 
				 String gameId = req.getParameter("gameId"); 			 
				 HttpSession session = req.getSession();
				 MemberVO member = (MemberVO) session.getAttribute("loginMember");
				 String memId = member.getMem_id();
				 
				 // 사용자의 구매완료 cartNO를 구해 gameId를 찾고, URL의 gameId를 비교해야됨
				 // 우선 구매한 gameId를 찾았다
				 List<String> orderedGameIdList = orderSerice.getOrderedGameId(memId);
				 System.out.println("\n\n orderedGameIdList의 목록 잘 뜨나 확인\n\n");
				 for(String or : orderedGameIdList) {
					 System.out.println(or+"\n");
				 }
				 boolean check = orderedGameIdList.contains(gameId);
				 System.out.println("\n\n 지금 구매하려는 게임Id가 order테이블에 존재합니까? => "+check+"\n\n");
				 
				 
				 
				 
				 if(check==true) {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1-1 이미 구매한 게임인경우
						msg="이미 구매한 게임입니다";
						
						session.setAttribute("msg", msg);
						
						//와 여기 오류 알았다 RedirectUrl에 
						String redirectUrl = req.getContextPath()+"/detailGame.do?id="+gameId;
						resp.sendRedirect(redirectUrl);
					
				 } else {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1-2 구매하지 않은 게임!!!!!!!!!!!!!
					 // 장바구니 테이블에 넣어주고 주문페이지로 넘어간다
					 // 그런데 구매는 안했으나 장바구니에는 이미 존재할수도 있음! 따라서 그것도 체크해줘야한다
					 
					 // 장바구니에 있는 내용을 가져오기
					 ICartService cartService = CartServiceImpl.getInstance();
					 List<CartVO> cartList = cartService.getCartList(memId);
					 List<String> cartIdList = new ArrayList<String>();
					 // 장바구니에 있는 내 게임중 id만 모아서 리스트 만듦
					 for(CartVO cart : cartList) {
						 cartIdList.add(cart.getGameId());
					 }
					 // 리스트에 gameId 존재하면 넘어가고 없으면 테이블에 추가작업
					 boolean isInCartChk = cartIdList.contains(gameId);
					 System.out.println("\n\n 장바구니에 존재하나요???? => "+isInCartChk+"\n\n");
					 
					 
					 if(isInCartChk == true) {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1-2-1 장바구니에 이미 그 게임이 존재하면 카트추가없이 넘어간다
						 String totalPrice = cartService.getPrice(gameId);
						 gamesIdList.add(gameId);
						// gameInfoList = orderSerice.getGamesInfo(gamesIdList);
						 
						 
						 IWishListService wishService = WishListServiceImpl.getInstance();
						 List<FreeGameVO> freeGameList = new ArrayList<FreeGameVO>();
						 if(wishService.freeGameInWish(gameId) != null) {
							 freeGameList.add(wishService.freeGameInWish(gameId));
						 }
						 req.setAttribute("freeGameList", freeGameList);
						 
						 if(freeGameList.isEmpty() == false) {
							 totalPrice = "0";
						 }
						 
						 req.setAttribute("totalPrice", totalPrice);
						 // 사려는 게임의 정보담은거
						 gameInfoList.add(orderSerice.getGamesInfo(gameId));
						 req.setAttribute("gameInfoList", gameInfoList);
						 // 사려는 게임의 카트번호
						 
						 System.out.println("getCartNo()에 넣을 첫번째 파라미터 : "+gameId);
						 System.out.println("getCartNo()에 넣을 두번째 파라미터 : "+memId);
						 cartNoList.add(orderSerice.getCartNo(gameId, memId));
						 
						 
						 System.out.println("사려는 게임의 카트번호 제발 들어와주ㅜㅜㅜㅜ"+cartNoList.get(0));
						 
						 req.setAttribute("cartNoList", cartNoList);
						 req.getRequestDispatcher("/orders/orderDetail.jsp").forward(req, resp);
						 
						 	
					 }else {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1-2-2 장바구니에도 존재하지 앟으면 카트테이블 추가해주고 넘어간다
							CartVO vo = new CartVO();
							vo.setMemId(memId);
							vo.setGameId(gameId);
							String price = cartService.getPrice(gameId);
							vo.setCartPrice(price);
							int cnt1 = cartService.insertCart(vo);
							int cnt2 = cartService.insertCartGame(gameId);	
								if(cnt1>0&&cnt2>0) {
									System.out.println("상세에서 구매 > Cart 테이블 잘 들어옴");
									System.out.println("상세에서 구매 > Cart_game 테이블 잘 들어옴");
								
									
									
									
									IWishListService wishService = WishListServiceImpl.getInstance();
									List<FreeGameVO> freeGameList = new ArrayList<FreeGameVO>();
									if(wishService.freeGameInWish(gameId) != null) {
										freeGameList.add(wishService.freeGameInWish(gameId));
									}
									req.setAttribute("freeGameList", freeGameList);
								
								// 주문페이지로 넘어가기 - 총가격과 게임인포리스트가 필요하다
								 String totalPrice = cartService.getPrice(gameId);
								 
								 // 한시적무료에 해당하면 가격 0으로 세팅해야함
								 if(freeGameList.isEmpty() == false) {
									 totalPrice = "0";
								 }
								 
								// gameInfoList = orderSerice.getGamesInfo(gamesIdList);
								 req.setAttribute("totalPrice", totalPrice);
								 
								 
								 gameInfoList.add(orderSerice.getGamesInfo(gameId));
								 req.setAttribute("gameInfoList", gameInfoList);
								 
								 
								 // 사려는 게임의 카트번호
								 cartNoList.add(orderSerice.getCartNo(gameId, memId));
								 
								 
								 
								 
								 req.setAttribute("cartNoList", cartNoList);
								 req.getRequestDispatcher("/orders/orderDetail.jsp").forward(req, resp);
								 
								 
								}else {
									System.out.println("상세에서 구매 > Cart 거쳐가기 미실행");
									String redirectUrl = req.getContextPath()+"/detailGame.do?id="+gameId;
									resp.sendRedirect(redirectUrl);
								}
					 }

				 }

			 

			 
		
		 }else { 
			 System.out.println("memId만 존재한다");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 2 장바구니에서 온 요청
			 
			 System.out.println("장바구니에서 온 요청");
			 //memId의 장바구니 싹다 List<VO>로 쿼리해와서setAttribute 
			 HttpSession session = req.getSession();
			MemberVO member = (MemberVO) session.getAttribute("loginMember");
			String memId = member.getMem_id();
			 
			 ICartService cartService = CartServiceImpl.getInstance();
			 
			 // 결제완료된거 제외한 카트리스트이다(cartPrice와 cartNo 가짐)
			 List<CartVO> selectCartList = cartService.getSelectCart(memId);
			 
			// 게임Id 알기위해 위 리스트 VO에 들어있는 cartNo로 정보 서치해주기 (gameId 가짐)
			List<String> selectGameList = new ArrayList<String>();
			for(CartVO vo : selectCartList) {
				selectGameList.add(cartService.getSelectGame(vo.getCartNo()));
			}
			// gameId를 이용하여 게임정보 가져오기
			for(String gameId : selectGameList) {
				gameInfoList.add(orderSerice.getGamesInfo(gameId));
			}
			// totalPrice jsp에서 겟
			String totalPrice = req.getParameter("totalPrice");
			
			// 카트No만!! 들어있는 리스트
			for(CartVO vo : selectCartList) {
				cartNoList.add(vo.getCartNo());
			}
			
			 // api로 넘겨줄 내용들!
		     // 총가격은 jsp로부터 받아옴
			 req.setAttribute("totalPrice", totalPrice);
			 // 한시적무료게임과 그 게임의 가격
			IWishListService wishService = WishListServiceImpl.getInstance();
			List<FreeGameVO> freeGameList = new ArrayList<FreeGameVO>();
			for(String vo : selectGameList) {
				if(wishService.freeGameInWish(vo) != null) {
					freeGameList.add(wishService.freeGameInWish(vo));
				}
			}
			req.setAttribute("freeGameList", freeGameList);
			 
			 // 사려는 게임의 기타정보
			 req.setAttribute("gameInfoList", gameInfoList);
			 // 사려는 게임의 카트번호
			 req.setAttribute("cartNoList", cartNoList);
			 
			 
			 req.getRequestDispatcher("/orders/orderDetail.jsp").forward(req, resp);
			 

			
		 }
		 

		 
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

}

orderDetail.jsp

<%@page import="java.util.List"%>
<%@page import="games.game.vo.GameVO"%>
<%@page import="orders.cart.vo.CartVO"%>
<%@page import="games.game.vo.FreeGameVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
           
<%

	String totalPrice = (String)request.getAttribute("totalPrice");	
	List<GameVO> gameInfoList = (List<GameVO>)request.getAttribute("gameInfoList");
	List<String> cartNoList = (List<String>)request.getAttribute("cartNoList");
	List<FreeGameVO> freeGameList = (List<FreeGameVO>)request.getAttribute("freeGameList");
	
%>
   
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="../css/pay.css">
</head>
<body>
	<div class="payment-summaries payment-summaries--mutiple">
		<span class="payment-title payment-summaries__title">주문 요약</span>
		
		<div><%=gameInfoList.size() %>개의 게임을 결제합니다</div>
		
		 	<%
				if(gameInfoList.size()>0){
					for(int i=0; i<gameInfoList.size(); i++){
			%>
			
			
		<div class="payment-summaries__scroll-container"
			id="payment-summaries__scroll-container">
			<div class="payment-offer-summary payment-offer-summary--mutiple">
				<div class="payment-offer-summary__content">
					<h2 class="payment-offer-summary__title"><%=gameInfoList.get(i).getGame_name() %></h2>
					<!-- <p class="payment-offer-summary__author">2K Games, Inc.</p> -->
					<span class="payment-offer-summary__origin-price"></span><span
						class="payment-offer-summary__current-price"><%=gameInfoList.get(i).getGame_price() %></span>
				</div>
				<div class="payment-offer-summary__thumbnail-wrap">
					<img alt="<%=gameInfoList.get(i).getGame_name() %>"
						src="<%=gameInfoList.get(i).getGame_img() %>"
						class="payment-offer-summary__thumbnail">
				</div>
			</div>
			<div class="payment-order-summary payment-summaries__order">
			
			
			
			
				<div class="payment-price">
					<div class="payment-price__label">
						<span>가격</span>
					</div>
					<div class="payment-price__value">
						<span>₩<%=gameInfoList.get(i).getGame_price() %></span>
					</div>
				</div>
				
				<%
					if(freeGameList.isEmpty()){ //한시적무료 없을때
				%>
	 				<div class="payment-price">
						<div class="payment-price__label">
							<span>판매 할인</span>
						</div>

						<div class="payment-price__value">
							-<span>₩0</span>
						</div>
					</div> 
				<%	
																				
					}else{ //한시적 무료 존재할때
						for(FreeGameVO vo : freeGameList){
							// 한시적무료게임의 경우
							if(vo.getGame_id().equals(gameInfoList.get(i).getGame_id())){
				%>
								<div class="payment-price">
									<div class="payment-price__label">
										<span>판매 할인</span>
									</div>
									
									<div class="payment-price__value">
										-<span>₩<%=gameInfoList.get(i).getGame_price() %></span>
									</div>
								</div> 
				<%
							} else{ // 한시적무료게임이 아닌경우
				%>	
								<div class="payment-price">
									<div class="payment-price__label">
										<span>판매 할인</span>
									</div>
			
									<div class="payment-price__value">
										-<span>₩0</span>
									</div>
								</div> 
				<%
								}
					}
					}
				%>
				<%	}} %>
				
				
				
				<!-- 여긴 하나만 출력  -->
				<hr class="payment-summaries__divider">
				<div class="payment-price">
					<div class="payment-price__label payment-price__label--YOUPAY">
						<span>합계</span>
					</div>
					<div class="payment-price__value payment-price__value--YOUPAY">
						<span>₩<%=totalPrice %></span>
					</div>
				</div>
			</div>
			<footer class="payment-contact-us">
				<p>
					<span>도움이 필요하신가요?</span>&nbsp;<a
						href="https://www.epicgames.com/help/ko/c99" target="_blank"
						rel="noopener noreferrer"><span>문의하기</span></a>
				</p>
			</footer>
		</div>
				
				<% 
					String cartNoPara="";
					int size2 = cartNoList.size();
					if(size2>0){
						for(int i=0; i<size2; i++){
							cartNoPara += "&cartNoPara"+"="+cartNoList.get(i);
						}
					}
				
					
				%>
				
				
		<%
			if(totalPrice.equals("0")){
				%>
						<div class="payment-order-confirm">
							<button class="payment-btn payment-order-confirm__btn payment-btn--disabled payment-btn--primary"
							onClick="location.href='../order/SuccessOrderController.do?><%=cartNoPara%>'">
								<div class="payment-loading">
									<div class="payment-loading__container">
										<span>주문하기</span>
									</div>
								</div>
							</button>
						</div>
				<%
			} else{
				%>
						<div class="payment-order-confirm">
							<button class="payment-btn payment-order-confirm__btn payment-btn--disabled payment-btn--primary"
							onClick="location.href='../order/kakaoPayController.do?totalPrice=<%=totalPrice%><%=cartNoPara%>'">
								<div class="payment-loading">
									<div class="payment-loading__container">
										<span>주문하기</span>
									</div>
								</div>
							</button>
						</div>
				<%
			}
		%>

		
	</div>
</body>
</html>

KakaoPayController

package orders.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import members.member.vo.MemberVO;
import orders.service.IOrderService;
import orders.service.OrderServiceImpl;


@WebServlet("/order/kakaoPayController.do")
public class KakaoPayController extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		System.out.println("카카오페이 doGet()");
		HttpSession session = req.getSession();
		MemberVO member = (MemberVO) session.getAttribute("loginMember");
		String memId = member.getMem_id();
		
		
		int totalPrice = Integer.parseInt(req.getParameter("totalPrice"));
		
		
		String[] cartNoParas = req.getParameterValues("cartNoPara");
		
        for (String elem : cartNoParas) {
            System.out.println("cartNoParas: " + elem);
        }
		
		// name, email, phone, totalPrice를 넘겨줘야한다.
		// memId를 이용해서 name, email, phone 찾아주기
		IOrderService service = OrderServiceImpl.getInstance();
		MemberVO vo = service.MemInfo(memId);
		String name=vo.getMem_name();
		String email = vo.getMem_mail();
		String phone = vo.getMem_ph();
		System.out.println(name);
		
		
		req.setAttribute("cartNoPara", cartNoParas);
		req.setAttribute("name", name);
		req.setAttribute("email", email);
		req.setAttribute("phone", phone);
		req.setAttribute("totalPrice", totalPrice);
		req.getRequestDispatcher("/orders/kakaoApi.jsp").forward(req, resp);
		
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

kakaoApi.jsp

<%@page import="orders.service.OrderServiceImpl"%>
<%@page import="orders.service.IOrderService"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.util.List"%>
<%
    String name =  (String)request.getAttribute("name");
    String email = (String)request.getAttribute("email");
    String phone = (String)request.getAttribute("phone");
    int totalPrice = (int)request.getAttribute("totalPrice");   
    String[] cartNoParas = (String[])request.getAttribute("cartNoPara");
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>아임포트 - 카카오페이 테스트</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js" ></script>
<script type="text/javascript" src="https://cdn.iamport.kr/js/iamport.payment-1.1.5.js"></script>
</head>
<body>
	<header id="header-container-fluid">
		<jsp:include page="/main/header.jsp"/>
		<jsp:include page="/main/headerNav.jsp"/>
	</header>
 <script>
    $(function(){
    	// !!결제 준비하기!!
        var IMP = window.IMP; // 생략가능
        IMP.init("imp06682244"); // "가맹점 식별코드"를 사용
        var msg;
        
        // !!결제 요청하기!!
       	//IMP.request_pay(param, callback) 결제창 호출
        IMP.request_pay({ 
        	// param
            pg : 'kakaopay',
            pay_method : 'card',
            merchant_uid : 'merchant_' + new Date().getTime(),
            name : '2PicGames 게임 결제 TEST',
            amount : '<%=totalPrice%>',
            buyer_email : '<%=email%>',
            buyer_name : '<%=name%>',
            buyer_tel : '<%=phone%>',
        }, function(rsp) { //콜백함수, rsp에는 결제결과 객체가 포함되어있다 (success(결제 성공 여부), paid_amount(결제된 금액), imp_uid(아임포트 거래 고유 번호) 등을 담고 있는 객체)
            if ( rsp.success ) {
                //[1] 서버단에서 결제정보 조회를 위해 jQuery ajax로 imp_uid 전달하기
               		jQuery.ajax({
                    url: "/payments/complete", //cross-domain error가 발생하지 않도록 주의해주세요
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        imp_uid : rsp.imp_uid
                        
                    }
                }).done(function(data) {
                    //[2] 서버에서 REST API로 결제정보확인 및 서비스루틴이 정상적인 경우
                    if ( everythings_fine ) {

                     } else {
                    	//결제중단시
                        //[3] 아직 제대로 결제가 되지 않았습니다.
                        //[4] 결제된 금액이 요청한 금액과 달라 결제를 자동취소처리하였습니다.
                    	msg = '결제중단';
                    }
                }); 
                //성공시 이동할 페이지
                
                        msg = '결제가 완료되었습니다.';
                        msg += '\n고유ID : ' + rsp.imp_uid;
                        msg += '\n상점 거래ID : ' + rsp.merchant_uid;
                        msg += '\결제 금액 : ' + rsp.paid_amount;
                        msg += '카드 승인번호 : ' + rsp.apply_num;
                                        
                        alert(msg);

                 <%-- location.href='<%=request.getContextPath()%>/order/paySuccess?msg='+msg; --%>

             	<% 
            	
            	int size = cartNoParas.length;
             	String cartNoParaLink ="";
            	if(size>0){
            		for(int i=0; i<size; i++){
            			cartNoParaLink += "&cartNoPara"+"="+cartNoParas[i];
            		}
            	}
         		System.out.println("APi단에서 파라미터 잘 들어왔나 ? : "+cartNoParaLink);
            	
            	%>

                 location.href='/order/SuccessOrderController.do?<%=cartNoParaLink%>';

            } else {
            	
            	
            	
                msg = '결제에 실패하였습니다.';
                msg += '\n에러내용 : ' + rsp.error_msg;
                //실패시 이동할 페이지
                <%-- location.href="<%=request.getContextPath()%>/order/payFail"; --%>
                alert(msg);
            }
        });
        
    });
    </script>
</body>
</html>

SuccessOrderController

package orders.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import orders.service.IOrderService;
import orders.service.OrderServiceImpl;

@WebServlet("/order/SuccessOrderController.do")
public class SuccessOrderController extends HttpServlet{
	
	// 결제완료했으니 order테이블에 성공한 내역 넣는 쿼리 작성하고 
	// 페이지 자체에선 여기서는 전체구매내역을 띄워볼까함
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		System.out.println("[결제 성공페이지] doget 들어왔다!");
		
		
		String[] cartNoList = req.getParameterValues("cartNoPara");
		for (String i : cartNoList) {
			System.out.print("성공페이지에 파라미터 무사히 들어왔니..? =>" + i);
		}
		
		

		IOrderService service = OrderServiceImpl.getInstance();
    	System.out.print("ORDER 디비에 결제성공한 CartNo 넣는 연산");    	
    	for(String cartNo : cartNoList){
    		service.insertOrder(cartNo);
    	}
		
    	String redirectUrl = req.getContextPath()+"/main/main.jsp";
		resp.sendRedirect(redirectUrl);
		
	}
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		
	}

}

0개의 댓글