먼저. 프로젝트 생성후 PROJECT\wshop\src\kr\or\dip\wshop 식으로 쇼핑몰 패키지를 생성한다.
패키지명은 kr.or.dip.wshop 으로 설정..패키지명은 이런 규칙으로 만들고..보통 자기 회사 네임에 맞게 설정한다.
kr.or.dip.wshop.buy
1. Buy.java
package kr.or.dip.wshop.buy;
import kr.or.dip.wshop.good.Good;
import kr.or.dip.wshop.customer.Customer;
public class Buy {
private long buyNum;
private long buyId;
private Good good;
private long qty;
private long buyPrice;
private String buyDate;
private Customer customer;
public String getBuyDate() {
return buyDate;
}
public void setBuyDate(String buyDate) {
this.buyDate = buyDate;
}
public long getBuyId() {
return buyId;
}
public void setBuyId(long buyId) {
this.buyId = buyId;
}
public long getBuyNum() {
return buyNum;
}
public void setBuyNum(long buyNum) {
this.buyNum = buyNum;
}
public long getBuyPrice() {
return buyPrice;
}
public void setBuyPrice(long buyPrice) {
this.buyPrice = buyPrice;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Good getGood() {
return good;
}
public void setGood(Good good) {
this.good = good;
}
public long getQty() {
return qty;
}
public void setQty(long gty) {
this.qty = gty;
}
}
2. BuyDAO.java
package kr.or.dip.wshop.buy;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import kr.or.dip.wshop.customer.Customer;
import kr.or.dip.wshop.good.ConnectionUtil;
import kr.or.dip.wshop.good.Good;
public class BuyDAO {
/*구매아이디를 생성하는 메서드*/
public static long getBuyId()throws Exception {
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
String sql=null;
long buyId=0;
try{
conn=ConnectionUtil.getConnection();
/*1.변수 sql에 SELECT max(buy_id) FROM buy 쿼리를 대입*/
sql = "SELECT max(buy_id)" + " FROM buy";
/*2.PrepareStatement 타입의 객체를 생성*/
psmt = conn.prepareStatement(sql);
/*3.SELECT 쿼리를 실행하고 rs에 검색결과 대입*/
rs=psmt.executeQuery();
/*5. 4의 rs에서 검색된 결과가 있다면 컬럼의 데이터를
* buyId=rs.getLong(1);
*/
if(rs.next())
{
buyId=rs.getLong(1);
}
}catch(Exception e){e.printStackTrace();
}finally{
try{rs.close();}catch(Exception e){ }
try{psmt.close();}catch(Exception e){ }
try{conn.close();}catch(Exception e){ }
}
/* 6. buyId 값을 1증가시킨후 리턴 */
return ++buyId;
}
/*구매번호를 생성하는 메서드*/
public static long getBuyNum()throws Exception {
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
String sql=null;
long buyNum=0;
try{
conn=ConnectionUtil.getConnection();
/*1.변수 sql에 SELECT max(buy_num) FROM buy 쿼리를 대입*/
sql = "SELECT max(buy_num)" + "FROM buy";
/*2.PrepareStatement 타입의 객체를 생성*/
psmt = conn.prepareStatement(sql);
/*3.SELECT 쿼리를 실행하고 rs에 검색결과 대입*/
rs=psmt.executeQuery();
/*5. 4의 rs에서 검색된 결과가 있다면 컬럼의 데이터를
* buyNum=rs.getLong(1);
*/
if(rs.next()){
buyNum=rs.getLong(1);
}
}catch(Exception e){e.printStackTrace();
}finally{
try{rs.close();}catch(Exception e){ }
try{psmt.close();}catch(Exception e){ }
try{conn.close();}catch(Exception e){ }
}
/* 6. buyNum 값을 1증가시킨후 String 으로 변환 해서 리턴 */
return ++buyNum;
}
/*구매 정보를 데이터 베이스에 저장하는 메서드*/
public static void insertBuy(long buyId,Buy buy)throws Exception {
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
String sql=null;
try{
conn=ConnectionUtil.getConnection();
/*1.변수 sql에 INSERT쿼리를 대입*/
sql = "INSERT INTO buy"+" (buy_num, buy_id, gid, qty, buy_Price, buy_date, customer_id)"+" values(?,?,?,?,?,now(),?)";
/*2.PreparedStatement 타입의 객체를 생성*/
psmt = conn.prepareStatement(sql);
/*3.long buyId=getBuyId()*/
// long buyId=BuyDAO.getBuyId();
/*4.2에서 생성한 객체의 ? 에 인자 student의
* 속성값을 get메서드를호출해서 대입
* buy_date->now()
* buy_id->buyId
* buy_num->getBuyNum()*/
psmt.setLong(1,BuyDAO.getBuyNum());
psmt.setLong(2,buyId);
psmt.setString(3,buy.getGood().getGid());
psmt.setLong(4,buy.getQty());
psmt.setLong(5,buy.getBuyPrice());
psmt.setString(6,buy.getCustomer().getCustomerId());
/*4.쿼리 실행*/
psmt.executeUpdate();
}catch(Exception e){e.printStackTrace();
}finally{
psmt.close();
conn.close();
}
}
/*구매 정보 검색 (customerId로) */
public static ArrayList SelectBuyList(String customerId)throws Exception {
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
String sql=null;
//Buy buy=null;
ArrayList<Buy> list = new ArrayList<Buy>();
try{
conn=ConnectionUtil.getConnection();
/*1.변수 sql에 SELECT buy_id,buy_date,sum(buy_price)
FROM buy WHERE customer_id=? Group by(buy_id) ; 쿼리를 대입
* */
sql="SELECT buy_id,buy_date,sum(buy_price) FROM buy WHERE customer_id=? Group by(buy_id)";
/*2.PreparedStatement 타입의 객체를 생성*/
psmt = conn.prepareStatement(sql);
/*3.2에서 생성한 객체의 ? 에 인자 customerId 대입 */
psmt.setString(1,customerId);
/*4.SELECT 쿼리를 실행하고 rs에 검색결과 대입*/
rs=psmt.executeQuery();
/*5. 4의 rs에서 검색된 결과가 있다면 Buy객체를 생성
* 각 컬럼의 데이터를 꺼내서 Buy 객체의
* set메서드를 호출해서 검색 결과를 대입*
*/
while(rs.next()){
Buy buy = new Buy();
buy.setBuyId(rs.getLong(1));
buy.setBuyDate(rs.getString(2));
buy.setBuyPrice(rs.getLong(3));
/*6. list에 5의 객체를 저장*/
list.add(buy);
}
}catch(Exception e){e.printStackTrace();
}finally{
psmt.close();
conn.close();
}
return list;
}
/*구매정보검색 (customerId와 buyId로)*/
public static ArrayList SelectBuyList(String customerId,long buyId)throws Exception {
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
String sql=null;
//Customer customer=null;
ArrayList<Buy> list = new ArrayList<Buy>();
try{
conn=ConnectionUtil.getConnection();
/*1.변수 sql에 SELECT쿼리를 대입
* */
sql = "SELECT b.buy_num,b.buy_id,b.gid,"+
"g.gname,g.price,b.qty,b.buy_price,"+
"b.buy_date,b.customer_id,c.customer_name" +
" FROM buy b, good g, customer c"+
" WHERE b.gid=g.gid AND " +
" b.customer_id=c.customer_id "+
" AND b.customer_id=? AND b.buy_id=?";
/*2.PreparedStatement 타입의 객체를 생성*/
psmt = conn.prepareStatement(sql);
/*3.2에서 생성한 객체의 ? 에 인자 customerId,buyId 대입 */
psmt.setString(1,customerId);
psmt.setLong(2, buyId);
/*4.SELECT 쿼리를 실행하고 rs에 검색결과 대입*/
rs=psmt.executeQuery();
/*5. 4의 rs에서 검색된 결과가 있다면 Buy객체를 생성
* 각 컬럼의 데이터를 꺼내서 Buy 객체의
* set메서드를 호출해서 검색 결과를 대입*/
while(rs.next()){
Buy buy = new Buy();
buy.setBuyNum(rs.getLong(1));
buy.setBuyId(rs.getLong(2));
Good good = new Good();
good.setGid(rs.getString(3));
good.setGname(rs.getString(4));
good.setPrice(rs.getLong(5));
buy.setGood(good);
buy.setQty(rs.getLong(6));
buy.setBuyPrice(rs.getLong(7));
buy.setBuyDate(rs.getString(8));
Customer customer=new Customer();
customer.setCustomerId(rs.getString(9));
customer.setCustomerName(rs.getString(10));
buy.setCustomer(customer);
/*6.list에 5의 객체 저장*/
list.add(buy);
}
}catch(Exception e){e.printStackTrace();
}finally{
psmt.close();
conn.close();
}
return list;
}
/*구매정보검색*/
public static Buy selectBuy(long buyNum)throws Exception {
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
String sql=null;
//Customer customer=null;
Buy buy = new Buy();
try{
conn=ConnectionUtil.getConnection();
/*1.변수 sql에 SELECT쿼리를 대입*/
sql = "SELECT b.buy_num,b.buy_id,b.gid,"+
"g.gname,g.price,b.qty,b.buy_price,"+
"b.buy_date,b.customer_id,c.customer_name" +
" FROM buy b, good g, customer c"+
" WHERE b.gid=g.gid AND " +
" b.customer_id=c.customer_id "+
" AND b.buy_num=?";
/*2.PreparedStatement 타입의 객체를 생성*/
psmt = conn.prepareStatement(sql);
/*3.2에서 생성한 객체의 ? 에 인자 customerId,buyNum 대입 */
psmt.setLong(1,buyNum);
/*4.SELECT 쿼리를 실행하고 rs에 검색결과 대입*/
rs=psmt.executeQuery();
/*5. 4의 rs에서 검색된 결과가 있다면 Buy객체를 생성
* 각 컬럼의 데이터를 꺼내서 Buy 객체의
* set메서드를 호출해서 검색 결과를 대입*/
if(rs.next()){
buy.setBuyNum(rs.getLong(1));
buy.setBuyId(rs.getLong(2));
Good good = new Good();
good.setGid(rs.getString(3));
good.setGname(rs.getString(4));
good.setPrice(rs.getLong(5));
buy.setGood(good);
buy.setQty(rs.getLong(6));
buy.setBuyPrice(rs.getLong(7));
buy.setBuyDate(rs.getString(8));
Customer customer=new Customer();
customer.setCustomerId(rs.getString(9));
customer.setCustomerName(rs.getString(10));
buy.setCustomer(customer);
}
/*6.list에 5의 객체 저장*/
}catch(Exception e){e.printStackTrace();
}finally{
psmt.close();
conn.close();
}
return buy;
}
public static void main(String args[]) throws Exception {
/*System.out.println("getByNum()"+BuyDAO.getBuyNum()); //4
System.out.println("getById()"+BuyDAO.getBuyId()); //3
long buyId=BuyDAO.getBuyId();
Buy buy1=new Buy();
Good good=new Good();
good.setGid("1");
buy1.setGood(good);
buy1.setQty(5);
buy1.setBuyPrice(250000);
Customer customer1 = new Customer();
customer1.setCustomerId("guest");
buy1.setCustomer(customer1);
Buy buy2=new Buy();
gid=2, gty=3,buyPrice=300000, customer_id=guest
* Buy 객체의 속성을 설정*/
/*Good good2 = new Good();
good2.setGid("2");
buy2.setGood(good2);
buy2.setQty(3);
buy2.setBuyPrice(300000);
Customer customer2 = new Customer();
customer2.setCustomerId("guest");
buy2.setCustomer(customer2);
BuyDAO.insertBuy(buyId,buy1);
BuyDAO.insertBuy(buyId,buy2);*/
/*Buy buy=BuyDAO.selectBuy(2);
System.out.println("buyId:"+buy.getBuyId());
System.out.println("buyNum:"+buy.getBuyNum());
System.out.println("gid:"+buy.getGood().getGid());
System.out.println("gname:"+buy.getGood().getGname());
System.out.println("price:"+buy.getGood().getPrice());
System.out.println("qty:"+buy.getQty());
System.out.println("buyPrice:"+buy.getBuyPrice());
System.out.println("buyDate:"+buy.getBuyDate());
System.out.println("customerId:"+buy.getCustomer().getCustomerId());
System.out.println("customerName:"+buy.getCustomer().getCustomerName());*/
/*ArrayList <Buy>list=BuyDAO.selectBuyList("guest");
for(int i=0;i<list.size();i++){
Buy buy=list.get(i);
System.out.println("buyId:"+buy.getBuyId());
System.out.println("buyPrice:"+buy.getBuyPrice());
System.out.println("buyDate:"+buy.getBuyDate()); */
ArrayList <Buy>list=BuyDAO.SelectBuyList("guest",1);
for(int i=0;i<list.size();i++){
Buy buy=list.get(i);
System.out.println("buyId:"+buy.getBuyId());
System.out.println("buyNum:"+buy.getBuyNum());
System.out.println("gid:"+buy.getGood().getGid());
System.out.println("gname:"+buy.getGood().getGname());
System.out.println("price:"+buy.getGood().getPrice());
System.out.println("qty:"+buy.getQty());
System.out.println("buyPrice:"+buy.getBuyPrice());
System.out.println("buyDate:"+buy.getBuyDate());
System.out.println("customerId:"+buy.getCustomer().getCustomerId());
System.out.println("customerName:"+buy.getCustomer().getCustomerName());
}
}
}
3. BuyService.java
package kr.or.dip.wshop.buy;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import kr.or.dip.wshop.customer.Customer;
import kr.or.dip.wshop.customer.CustomerDAO;
import kr.or.dip.wshop.good.Good;
import kr.or.dip.wshop.good.GoodDAO;
/**
* Servlet implementation class for Servlet: BuyService
*
*/
public class BuyService extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public BuyService() {
super();
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String method = request.getParameter("method");
if(method==null)
method="addBuy";
try{
if(method.equalsIgnoreCase("addBuy")){
addBuy(request,response);
}else if(method.equalsIgnoreCase("viewBuyList")){
viewBuyList(request, response);
}else if(method.equalsIgnoreCase("viewBuyDetailList")){
viewBuyDetailList(request,response);
}
}catch(Exception e){
e.printStackTrace();
}
}
//자세한 구매 내역 확인
public static void viewBuyDetailList(HttpServletRequest request,
HttpServletResponse response) throws Exception{
//1.파라메터에서 buyId를 꺼내서 변수에 대입
String buyId = request.getParameter("buyId");
//2.세션객체를 얻어옴(생성하지 말것)
HttpSession session = request.getSession(false);
/*3.세션객체가 없다면 로그인 페이지로 이동
* -> request.getConTextPath()+/Customer*/
if(session==null){
response.sendRedirect(request.getContextPath()+"/Customer");
return;
}
/*4.세션의 CUSTOMER 속성을 변수에 대입*/
Object o = session.getAttribute("CUSTOMER");
/*5.4가 null 이면 로그인 페이지로 이동
* -> request.getContextPath()+/Customer*/
if(o==null){
response.sendRedirect(request.getContextPath()+"/Customer");
return;
}
/*6.4의 객체를 Customer 타입 customer 에 대입*/
Customer customer = (Customer)o;
/*7.ArrayList list=
* BuyDAO.selectBuyList(customer.getCustomerId(),
* Long.parseLong(buyId))*/
ArrayList list = BuyDAO.SelectBuyList(customer.getCustomerId(),Long.parseLong(buyId));
/*8.7의 list를 request에 BUY_LIST 속성으로 저장*/
request.setAttribute("BUY_LIST", list);
/*9.RequestDispatcher 를 이용 /buy/viewBuyDetailList.jsp 로 이동*/
RequestDispatcher rd=request.getRequestDispatcher("/buy/viewBuyDetailList.jsp");
rd.forward(request,response);
}
// 구매내역 확인
public static void viewBuyList(HttpServletRequest request, HttpServletResponse response) throws Exception{
/*1. 세션 객체를 얻어옴 (생성하지 말것) */
HttpSession session=request.getSession(false);
/*2. 세션 객체가 없다면 /Good 으로 이동*/
if(session==null){
RequestDispatcher rd=request.getRequestDispatcher("/Good");
rd.forward(request, response);
return;
}
/*3. 세션에서 CUSTOMER 속성을 꺼내기 */
Object o = session.getAttribute("CUSTOMER");
/*4. 세션에 CUSTOMER 속성이 없다면 로그인 페이지로 이동
* ->request.getContextPath()+/Customer*/
if(o==null){
response.sendRedirect(request.getContextPath()+"/Customer");
return;
}
/*5. 3의 객체를 Customer 타입의 변수 customer에 대입 */
Customer customer = (Customer)o;
/*6. BuyDAO.SelectBuyList(Customer.getCustomerId())
* 호출*/
ArrayList list= BuyDAO.SelectBuyList(customer.getCustomerId());
/*7. 6에서 리턴된 ArrayList 객체를 request에 BUY_LIST
* 라는 속성명으로 저장*/
request.setAttribute("BUY_LIST", list);
/*8. RequestDispatcher 를 이용해서 viewBuyList.jsp로 이동*/
RequestDispatcher rd=request.getRequestDispatcher("/buy/viewBuyList.jsp");
rd.forward(request,response);
}
public static void addBuy
(HttpServletRequest request, HttpServletResponse response) throws Exception{
HttpSession session = request.getSession(false);
if(session == null){
response.sendRedirect(request.getContextPath()+"/Good");
return;
}
String total="0";//구입 금액 합계
/*1.세션에서 장바구니 cart 를 꺼내서
* ArrayList 타입의 변수에 대입한다.*/
ArrayList <Good>cart=new ArrayList<Good>();
Object o=session.getAttribute("cart");
if(o!=null)
cart=(ArrayList)o;
/*2. 1 의 ArrayList 에서 각각의 Good 객체를 꺼내서
*for 문을 돌면서 구입 금액의 합계를 구해
* total에 대입한다.*/
long totalPrice=0;
long buyId=BuyDAO.getBuyId();
for(int i=0;i<cart.size();i++){
Good good=cart.get(i);
totalPrice+=good.getPrice()*good.getGty();
Buy buy = new Buy();
buy.setGood(good);
buy.setQty(good.getGty());
buy.setBuyPrice(good.getGty()*good.getPrice());
Object c = session.getAttribute("CUSTOMER");
Customer customer = (Customer)c;
buy.setCustomer(customer);
BuyDAO.insertBuy(buyId, buy);
}
total=new Long(totalPrice).toString();
/*3.request 객체에 total 을 total 이라는
*이름으로 저장
**/
request.setAttribute("total",total);
RequestDispatcher rd=
request.getRequestDispatcher("/good/buy.jsp");
rd.forward(request,response);
}
}
4. CartService.java
package kr.or.dip.wshop.buy;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import kr.or.dip.wshop.good.Good;
/**
* Servlet implementation class for Servlet: CartService
*
*/
public class CartService extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public CartService() {
super();
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("euc-kr");
String gid = request.getParameter("gid");
if(gid==null){
response.sendRedirect(request.getContextPath()+"/Good");
return;
}
/*세션이 없거나 세션에 로그인 정보가 없으면
*로그인 페이지로 이동*/
HttpSession session=request.getSession(false); // 원래 있던 세션 리턴받기 (false)
if(session==null){
RequestDispatcher rd=request.getRequestDispatcher("/Customer"); // 서블릿 주소 불러오기
rd.forward(request, response);
return;
}
Object customer = session.getAttribute("CUSTOMER");
if(customer==null){
RequestDispatcher rd=request.getRequestDispatcher("/Customer");
rd.forward(request, response);
return;
}
String gname=request.getParameter("gname");
String price=request.getParameter("price");
Good good=new Good();
good.setGid(gid);
good.setGname(gname);
good.setPrice(Long.parseLong(price));
//HttpSession session=request.getSession();
Object o=session.getAttribute("cart");
ArrayList<Good> cart=new ArrayList<Good>();
if(o!=null)
cart=(ArrayList)o;
//cart.add(good);
int searchIndex=cart.indexOf(good);
Good searchGood=null;
if(searchIndex<0){
cart.add(good);
}else{
searchGood=cart.get(searchIndex);
searchGood.setGty(searchGood.getGty()+1);
cart.set(searchIndex,searchGood);
}
request.setAttribute("good",good);
session.setAttribute("cart",cart);
RequestDispatcher rd=
request.getRequestDispatcher("/good/cart.jsp");
rd.forward(request, response);
}
}




덧글