고양이달리 2023. 9. 7. 22:04

product.java

ackage product;
public class Product {
	private int num;
	private String name;
	private int price;
	private int amount;
	private String seller;

	public Product() {
	}

	public Product(int num, String name, int price, int amount, String seller) {
		this.num = num;
		this.name = name;
		this.price = price;
		this.amount = amount;
		this.seller = seller;
	}


	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

	public int getAmount() {
		return amount;
	}

	public void setAmount(int amount) {
		this.amount = amount;
	}

	public String getSeller() {
		return seller;
	}

	public void setSeller(String seller) {
		this.seller = seller;
	}

	@Override
	public String toString() {
		return "Product [num=" + num + ", name=" + name + ", price=" + price + ", amount=" + amount + ", seller="
				+ seller + "]";
	}

}

productDao

package product;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import conn.DBConnect;

public class ProductDao {
	private DBConnect dbconn;

	public ProductDao() {
		dbconn = DBConnect.getInstance();
	}

	// 상품추가: insert

	public void insert(Product p) {
		Connection conn = dbconn.conn();

		String sql = "insert into product values(seq_prod.nextval,?,?,?,?)";

		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);

			pstmt.setString(1, p.getName());
			pstmt.setInt(2, p.getPrice());
			pstmt.setInt(3, p.getAmount());
			pstmt.setString(4, p.getSeller());

			int cnt = pstmt.executeUpdate();
			System.out.println(cnt + "개의 상품이 추가되었습니다.");

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	// 상품번호로 검색: select. 한 개 검색
	public Product select(int num) {// Product 한 개를 검색한 결과
		Connection conn = dbconn.conn();

		String sql = "select * from product where num=?";

		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);

			pstmt.setInt(1, num);

			ResultSet rs = pstmt.executeQuery();

			if (rs.next()) {
				return new Product(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getString(5));
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// 제품명으로 검색: selectByName(). 여러 개 검색=>arraylist
	public ArrayList<Product> selectByName(String name) {
		ArrayList<Product> list= new ArrayList<>(); 
		
		Connection conn = dbconn.conn();

		String sql = "select * from product where name = ?";

		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);

			pstmt.setString(1, "%"+name+"%");

			ResultSet rs = pstmt.executeQuery();

			while (rs.next()) {
				list.add(new Product(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getString(5)));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return list;
	}

	// 가격대로 검색: selectByPrice(). 1000~2000 사이의 제품. 여러 개 검색
	public ArrayList<Product> selectByPrice(int price1, int price2) {
		ArrayList<Product> list= new ArrayList<>(); 
		
		Connection conn = dbconn.conn();

		String sql = "select * from product where price between ? and ?";

		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);

			pstmt.setInt(1, price1);
			pstmt.setInt(2, price2);

			ResultSet rs = pstmt.executeQuery();

			if (rs.next()) {
				list.add( new Product(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getString(5)));
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return list;
	}

	// 전체 검색: selectAll()
	public ArrayList<Product> selectAll() {
		ArrayList<Product> list = new ArrayList<Product>();

		Connection conn = dbconn.conn();

		String sql = "select * from product";

		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);

			ResultSet rs = pstmt.executeQuery();

			while (rs.next()) {
				list.add(new Product(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getString(5)));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return list;
	}

	// 판매자로 검색: selectBySeller(). 여러 개 검색.
	public ArrayList<Product> selectBySeller(String seller) {
		ArrayList<Product> list = new ArrayList<Product>();
		
		Connection conn = dbconn.conn();

		String sql = "select * from product where seller = ?";

		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, seller);

			ResultSet rs = pstmt.executeQuery();

			while (rs.next()) {
				list.add(new Product(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getString(5)));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return list;
	}

	// 수정: update(). 본인 상품만 수정 가능
	public void update(Product p) {
		Connection conn = dbconn.conn();

		String sql = "update product set price=? where num=?";

		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);

			pstmt.setInt(1, p.getPrice());
			pstmt.setInt(2, p.getNum());

			int cnt = pstmt.executeUpdate();
			System.out.println(cnt + "개의 상품이 수정되었습니다.");

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	// 삭제: delete(). 본인 상품만 삭제 가능
	public void delete(int num) {
		Connection conn = dbconn.conn();

		String sql = "delete from product where num=?";

		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);
			
			pstmt.setInt(1, num);

			int cnt = pstmt.executeUpdate();
			System.out.println(cnt + "개의 상품이 삭제되었습니다.");

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}

productService

package product;

import java.util.ArrayList;

public class ProductService {
	private ProductDao dao;
	
	public ProductService() {
		dao = new ProductDao();
	}
	
	public void addProduct(Product p) {
		dao.insert(p);
	}
	
	public ArrayList<Product> getAll(){
		return dao.selectAll();
	}
	
	public Product getProduct(int num) {
		return dao.select(num);
	}
	
	public ArrayList<Product> getByName(String name) {
		return dao.selectByName(name);
	}
	
	
	public ArrayList<Product> getBySeller(String seller) {
		return dao.selectBySeller(seller);
	}
	
	
	public ArrayList<Product> getByPrice(int price1, int price2){
		return dao.selectByPrice(price1, price2);
	}
	
	public void delProduct(int num) {
		dao.delete(num);
	}
	
	public void editProduct(Product p) {
		dao.update(p);
	}
}

AddProduct.java

package product.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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 product.Product;
import product.ProductService;

/**
 * Servlet implementation class AddProduct
 */
@WebServlet("/product/add")
public class AddProduct extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddProduct() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//상품등록 페이지로 이동
		RequestDispatcher dis = request.getRequestDispatcher("/product/add.jsp");
		dis.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//한글로 인코딩하기(서블릿마다 추가해야 함)
		request.setCharacterEncoding("euc-kr");
		response.setCharacterEncoding("euc-kr");
		
		String name = request.getParameter("name");
		int price = Integer.parseInt(request.getParameter("price"));
		int amount = Integer.parseInt(request.getParameter("amount"));
		String seller = request.getParameter("seller");
		
		//db에 넣기
		ProductService service = new ProductService();
		service.addProduct(new Product(0, name, price, amount, seller));
		
		//이동할 페이지. 
		//list.jsp로 가면 안됨. 서블릿으로 가서 검색을 한 다음에 페이지에 뿌려주어야 한다는 것을 명심하자.
		//forward를 이용하면 새로 고침시 (이전에 입력한 데이터로) 상품이 자동 추가되므로 redirect를 사용한다.
		//Redirect: 클라이언트에 새로 요청. 새로 고침 시 이전 동작 반복을 하지 않는다.
		response.sendRedirect("/app1/product/list");
	}

}

add.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<h3>상품 등록</h3>
	<form action="/app1//product/add" method="post">
		<table border="1">

			<tr>
				<th>상품명</th>
				<td><input type="text" name="name"></td>
			</tr>
			<tr>
				<th>가격</th>
				<td><input type="number" name="price"></td>
			</tr>
			<tr>
				<th>수량</th>
				<td><input type="number" name="amount"></td>
			</tr>
			<tr>
				<th>판매자</th>
				<td><input type="text" name="seller" value="${sessionScope.loginId }" readonly></td>
			</tr>
			<tr>
				<th>등록</th>
				<td><input type="submit" value="등록"></td>
			</tr>
		</table>
	</form>
</body>
</html>

ListProduct.java

package product.controller;

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

import javax.servlet.RequestDispatcher;
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 product.Product;
import product.ProductService;

/**
 * Servlet implementation class ListProduct
 */
@WebServlet("/product/list")
public class ListProduct extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListProduct() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//전체검색을 하려면 Service가 필요하니까 객체 생성
		ProductService service = new ProductService();
		ArrayList<Product> list = service.getAll();
		
		//request에 담기
		request.setAttribute("list", list);
		RequestDispatcher dis = request.getRequestDispatcher("/product/list.jsp");
		dis.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}