기본 구조 세팅은 blog 만들기에서 가져왔다
시작세팅
데이터베이스에서 테이블을 만들자
물건 타입을 설정하는 테이블
CREATE TABLE PRODUCTTYPE
(
PTYPE VARCHAR2(100) NOT NULL
, CONSTRAINT PRODUCTTYPE_PK PRIMARY KEY
(
PTYPE
)
ENABLE
);
product테이블
CREATE TABLE PRODUCT
(
ID NUMBER NOT NULL
, NAME VARCHAR2(100)
, TYPE VARCHAR2(100)
, PRICE NUMBER
, COUNT NUMBER
, CONSTRAINT PRODUCT_PK PRIMARY KEY
(
ID
)
ENABLE
);
ALTER TABLE PRODUCT
ADD CONSTRAINT PRODUCT_FK1 FOREIGN KEY
(
TYPE
)
REFERENCES PRODUCTTYPE
(
PTYPE
)
ON DELETE SET NULL ENABLE;
type는 producttype의 값을 외래키로 가진다
(producttype 튜플이 삭제되면 해당 타입은 널값이된다)
시퀀스
CREATE SEQUENCE PRODUCT_SEQ INCREMENT BY 1 START WITH 1;
db 만들기
package com.jaybon.product.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DBConn {
public static Connection getConnection() {
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();
PreparedStatement pstmt;
ResultSet rs;
System.out.println("DBConn : 데이터베이스 연결성공");
return conn;
} catch (Exception e) {
e.printStackTrace();
System.out.println("DBConn : 데이터베이스 연결실패");
System.out.println("DBConn : Message : " + e.getMessage());
}
return null;
}
public static void close(Connection conn, PreparedStatement pstmt) {
try {
conn.close();
pstmt.close();
} catch (Exception e) {
System.out.println("DB종료시 오류가 발생 : " + e.getMessage());
}
}
public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs) {
try {
conn.close();
pstmt.close();
rs.close();
} catch (Exception e) {
System.out.println("DB종료시 오류가 발생 : " + e.getMessage());
}
}
}
model 만들기
package com.jaybon.product.model;
public enum ProductType {
과일, 문구, 옷
}
action 만들기
action 인터페이스
package com.jaybon.product.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface Action {
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException;
}
ProductTestAction
package com.jaybon.product.action.product;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jaybon.product.action.Action;
import com.jaybon.product.model.Product;
import com.jaybon.product.repository.ProductRepository;
public class ProductTestAction implements Action{
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("ProductTestAction");
ProductRepository productRepository = ProductRepository.getInstance();
List<Product> products = productRepository.findAll();
request.setAttribute("products", products);
System.out.println("홈페이지 이동합니다.");
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
}
ProductGoFirstProcAction
package com.jaybon.product.action.product;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.jaybon.product.action.Action;
import com.jaybon.product.model.Product;
import com.jaybon.product.repository.ProductRepository;
public class ProductGoFirstProcAction implements Action{
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
ProductRepository productRepository = ProductRepository.getInstance();
List<Product> products = productRepository.findAll();
String productsJson = gson.toJson(products);
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charser=utf-8");
PrintWriter pw = response.getWriter();
pw.println(productsJson);
}
}
ProductPriceAscProcAction
package com.jaybon.product.action.product;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.jaybon.product.action.Action;
import com.jaybon.product.model.Product;
import com.jaybon.product.repository.ProductRepository;
public class ProductPriceAscProcAction implements Action{
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
ProductRepository productRepository = ProductRepository.getInstance();
List<Product> products = productRepository.findAllPriceAsc();
String productsJson = gson.toJson(products);
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charser=utf-8");
PrintWriter pw = response.getWriter();
pw.println(productsJson);
}
}
ProductPriceDescProcAction
package com.jaybon.product.action.product;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.jaybon.product.action.Action;
import com.jaybon.product.model.Product;
import com.jaybon.product.repository.ProductRepository;
public class ProductPriceDescProcAction implements Action{
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
ProductRepository productRepository = ProductRepository.getInstance();
List<Product> products = productRepository.findAllPriceDesc();
String productsJson = gson.toJson(products);
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charser=utf-8");
PrintWriter pw = response.getWriter();
pw.println(productsJson);
}
}
ProductCountDescProcAction
package com.jaybon.product.action.product;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.jaybon.product.action.Action;
import com.jaybon.product.model.Product;
import com.jaybon.product.repository.ProductRepository;
public class ProductCountDescProcAction implements Action{
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
ProductRepository productRepository = ProductRepository.getInstance();
List<Product> products = productRepository.findAllCountDesc();
String productsJson = gson.toJson(products);
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charser=utf-8");
PrintWriter pw = response.getWriter();
pw.println(productsJson);
}
}
ProductDeleteProcAction
package com.jaybon.product.action.product;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.jaybon.product.action.Action;
import com.jaybon.product.model.Product;
import com.jaybon.product.repository.ProductRepository;
public class ProductDeleteProcAction implements Action{
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int productId = Integer.parseInt(request.getParameter("productId"));
ProductRepository productRepository = ProductRepository.getInstance();
int result = productRepository.deleteById(productId);
if(result == 1) {
List<Product> products = productRepository.findAll();
Gson gson = new Gson();
String productsJson = gson.toJson(products);
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charser=utf-8");
PrintWriter pw = response.getWriter();
pw.println(productsJson);
}
}
}
controller 만들기
package com.jaybon.product.controller;
import java.io.IOException;
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 com.jaybon.product.action.Action;
import com.jaybon.product.action.product.ProductCountDescProcAction;
import com.jaybon.product.action.product.ProductDeleteProcAction;
import com.jaybon.product.action.product.ProductGoFirstProcAction;
import com.jaybon.product.action.product.ProductPriceAscProcAction;
import com.jaybon.product.action.product.ProductPriceDescProcAction;
import com.jaybon.product.action.product.ProductTestAction;
// http://localhost:8000/blog/user
@WebServlet("/test")
public class ProductController extends HttpServlet {
private final static String TAG = "ProductController : ";
private static final long serialVersionUID = 1L;
public ProductController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doProcess(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// http://localhost:8000/product/user?cmd=test
String cmd = request.getParameter("cmd");
System.out.println(TAG + "router : " + cmd);
Action action = router(cmd);
action.execute(request, response);
}
public Action router(String cmd) {
if (cmd.equals("home")) {
return new ProductTestAction();
} else if (cmd.equals("goFirstProc")) {
return new ProductGoFirstProcAction();
} else if (cmd.equals("priceAscProc")) {
return new ProductPriceAscProcAction();
} else if (cmd.equals("priceDescProc")) {
return new ProductPriceDescProcAction();
} else if (cmd.equals("countDescProc")) {
return new ProductCountDescProcAction();
} else if (cmd.equals("deleteProc")) {
return new ProductDeleteProcAction();
}
return null;
}
}
repository 만들기
package com.jaybon.product.repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.jaybon.product.db.DBConn;
import com.jaybon.product.model.Product;
import com.jaybon.product.model.ProductType;
public class ProductRepository {
private static final String TAG = "ProductRepository : "; // TAG 생성 (오류 발견시 용이)
private static ProductRepository instance = new ProductRepository();
private ProductRepository() {
}
public static ProductRepository getInstance() {
return instance;
}
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
public int deleteById(int id) {
final String SQL = "DELETE FROM product WHERE id =?";
List<Product> products = null;
try {
conn = DBConn.getConnection(); // DB에 연결
pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1, id);
int result = pstmt.executeUpdate();
return result;
} catch (SQLException e) {
e.printStackTrace();
System.out.println(TAG + "deleteById : " + e.getMessage());
} finally {
DBConn.close(conn, pstmt, rs);
}
return -1; // 실패시
}
// product 다찾기
public List<Product> findAll() { // object 받기(안에 내용 다 받아야 하니까)
final String SQL = "SELECT id, name, type, price, count FROM product ORDER BY id asc";
List<Product> products = null;
try {
conn = DBConn.getConnection(); // DB에 연결
pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
if(rs.next()) {
products = new ArrayList<>();
Product product = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product);
while (rs.next()) {
Product product1 = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product1);
}
}
return products;
} catch (SQLException e) {
e.printStackTrace();
System.out.println(TAG + "findAll : " + e.getMessage());
} finally {
DBConn.close(conn, pstmt, rs);
}
return null; // 실패시
}
public List<Product> findAllPriceAsc() { // object 받기(안에 내용 다 받아야 하니까)
final String SQL = "SELECT id, name, type, price, count FROM product ORDER BY Price ASC";
List<Product> products = null;
try {
conn = DBConn.getConnection(); // DB에 연결
pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
if(rs.next()) {
products = new ArrayList<>();
Product product = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product);
while (rs.next()) {
Product product1 = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product1);
}
}
return products;
} catch (SQLException e) {
e.printStackTrace();
System.out.println(TAG + "findAll : " + e.getMessage());
} finally {
DBConn.close(conn, pstmt, rs);
}
return null; // 실패시
}
public List<Product> findAllPriceDesc() { // object 받기(안에 내용 다 받아야 하니까)
final String SQL = "SELECT id, name, type, price, count FROM product ORDER BY Price DESC";
List<Product> products = null;
try {
conn = DBConn.getConnection(); // DB에 연결
pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
if(rs.next()) {
products = new ArrayList<>();
Product product = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product);
while (rs.next()) {
Product product1 = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product1);
}
}
return products;
} catch (SQLException e) {
e.printStackTrace();
System.out.println(TAG + "findAll : " + e.getMessage());
} finally {
DBConn.close(conn, pstmt, rs);
}
return null; // 실패시
}
public List<Product> findAllCountDesc() { // object 받기(안에 내용 다 받아야 하니까)
final String SQL = "SELECT id, name, type, price, count FROM product ORDER BY count DESC";
List<Product> products = null;
try {
conn = DBConn.getConnection(); // DB에 연결
pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
if(rs.next()) {
products = new ArrayList<>();
Product product = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product);
while (rs.next()) {
Product product1 = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product1);
}
}
return products;
} catch (SQLException e) {
e.printStackTrace();
System.out.println(TAG + "findAll : " + e.getMessage());
} finally {
DBConn.close(conn, pstmt, rs);
}
return null; // 실패시
}
}
index.jsp 만들기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
response.sendRedirect("/product/test?cmd=home");
%>
테스트 결과
home.jsp 만들기
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Product</h2>
<p>The .table-striped class adds zebra-stripes to a table:</p>
<div class="btn-group">
<button onclick="goFirst()" type="button" class="btn btn-primary">처음으로</button>
<button onclick="priceAsc()" type="button" class="btn btn-success">가격 오름차순</button>
<button onclick="priceDesc()" type="button" class="btn btn-warning">가격 내림차순</button>
<button onclick="countDesc()" type="button" class="btn btn-danger">판매순</button>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>번호</th>
<th>이름</th>
<th>종류</th>
<th>가격</th>
<th>판매수</th>
<th> </th>
</tr>
</thead>
<tbody id="my__tbody">
<c:forEach var="product" items="${products}">
<tr id="product-${product.id}">
<td>${product.id}</td>
<td>${product.name}</td>
<td>${product.type}</td>
<td>${product.price}</td>
<td>${product.count}</td>
<td><i class="large material-icons" onclick="deleteItem(${product.id})" style="cursor:pointer;">delete_forever</i></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<script>
function append(result) {
for (var product of result){
var string =
" <tr id=\"product-"+product.id+"\">\r\n" +
" <td>"+product.id+"</td>\r\n" +
" <td>"+product.name+"</td>\r\n" +
" <td>"+product.type+"</td>\r\n" +
" <td>"+product.price+"</td>\r\n" +
" <td>"+product.count+"</td>\r\n" +
" <td><i class=\"large material-icons\" onclick=\"deleteItem("+product.id+")\" style=\"cursor:pointer;\">delete_forever</i></td>" +
" </tr>";
$('#my__tbody').append(string);
}
}
function deleteItem(productId) {
console.log(productId);
$.ajax({
type : "get",
url : "/product/test?cmd=deleteProc&productId="+productId,
dataType : "json"
}).done(function (result) {
$("#my__tbody").empty();
alert("삭제에 성공하였습니다.");
append(result);
}).fail(function (result) {
alert("삭제에 실패하였습니다.");
});
}
function goFirst() {
$.ajax({
type : "get",
url : "/product/test?cmd=goFirstProc",
dataType : "json"
}).done(function (result) {
$("#my__tbody").empty();
append(result);
}).fail(function (result) {
});
}
function priceAsc() {
$.ajax({
type : "get",
url : "/product/test?cmd=priceAscProc",
dataType : "json"
}).done(function (result) {
$("#my__tbody").empty();
append(result);
}).fail(function (result) {
});
}
function priceDesc() {
$.ajax({
type : "get",
url : "/product/test?cmd=priceDescProc",
dataType : "json"
}).done(function (result) {
$("#my__tbody").empty();
append(result);
}).fail(function (result) {
});
}
function countDesc() {
$.ajax({
type : "get",
url : "/product/test?cmd=countDescProc",
dataType : "json"
}).done(function (result) {
$("#my__tbody").empty();
append(result);
}).fail(function (result) {
});
}
</script>
</body>
</html>
테스트 결과
리스트에 아이템 추가하기
home.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Product</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Product</h2>
<form action="/product/test?cmd=insertItem" method="post">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">아이템 추가</span>
</div>
<input name="productName" type="text" class="form-control" placeholder="이름" required="required">
<select name='productType' size='1' required="required">
<option value='' selected>종류선택</option>
<option value='옷'>옷</option>
<option value='과일'>과일</option>
<option value='문구'>문구</option>
</select>
<input name="productPrice" type="text" class="form-control" placeholder="가격" required="required">
<input name="productCount" type="text" class="form-control" placeholder="판매수" required="required">
<button type="submit">추가하기</button>
</div>
</form>
<div class="btn-group">
<button onclick="goFirst()" type="button" class="btn btn-primary">처음으로</button>
<button onclick="priceAsc()" type="button" class="btn btn-success">가격 오름차순</button>
<button onclick="priceDesc()" type="button" class="btn btn-warning">가격 내림차순</button>
<button onclick="countDesc()" type="button" class="btn btn-danger">판매순</button>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>번호</th>
<th>이름</th>
<th>종류</th>
<th>가격</th>
<th>판매수</th>
<th> </th>
</tr>
</thead>
<tbody id="my__tbody">
<c:forEach var="product" items="${products}">
<tr id="product-${product.id}">
<td>${product.id}</td>
<td>${product.name}</td>
<td>${product.type}</td>
<td>${product.price}</td>
<td>${product.count}</td>
<td><i class="large material-icons" onclick="deleteItem(${product.id}, 'goFirst')" style="cursor:pointer;">delete_forever</i></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<script>
function append(result, listType) {
for (var product of result){
var string =
" <tr id=\"product-"+product.id+"\">\r\n" +
" <td>"+product.id+"</td>\r\n" +
" <td>"+product.name+"</td>\r\n" +
" <td>"+product.type+"</td>\r\n" +
" <td>"+product.price+"</td>\r\n" +
" <td>"+product.count+"</td>\r\n" +
" <td><i class=\"large material-icons\" onclick=\"deleteItem("+product.id+")\" style=\"cursor:pointer;\">delete_forever</i></td>" +
" </tr>";
$('#my__tbody').append(string);
}
}
function deleteItem(productId) {
console.log(productId);
$.ajax({
type : "get",
url : "/product/test?cmd=deleteProc&productId="+productId,
dataType : "json"
}).done(function (result) {
if(result == "1"){
$("#product-"+productId).remove();
alert("삭제에 성공하였습니다.");
} else{
alert("삭제에 실패하였습니다.");
}
// $("#my__tbody").empty();
// append(result);
}).fail(function (result) {
alert("삭제에 실패하였습니다.");
});
}
function goFirst() {
$.ajax({
type : "get",
url : "/product/test?cmd=goFirstProc",
dataType : "json"
}).done(function (result) {
$("#my__tbody").empty();
append(result);
}).fail(function (result) {
});
}
function priceAsc() {
$.ajax({
type : "get",
url : "/product/test?cmd=priceAscProc",
dataType : "json"
}).done(function (result) {
$("#my__tbody").empty();
append(result);
}).fail(function (result) {
});
}
function priceDesc() {
$.ajax({
type : "get",
url : "/product/test?cmd=priceDescProc",
dataType : "json"
}).done(function (result) {
$("#my__tbody").empty();
append(result, "priceDesc");
}).fail(function (result) {
});
}
function countDesc() {
$.ajax({
type : "get",
url : "/product/test?cmd=countDescProc",
dataType : "json"
}).done(function (result) {
$("#my__tbody").empty();
append(result);
}).fail(function (result) {
});
}
</script>
</body>
</html>
폼으로 데이터 전송
ProductController
ProductInsertItemProcAction
package com.jaybon.product.action.product;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jaybon.product.action.Action;
import com.jaybon.product.model.Product;
import com.jaybon.product.model.ProductType;
import com.jaybon.product.repository.ProductRepository;
import jdk.nashorn.internal.ir.RuntimeNode.Request;
public class ProductInsertItemProcAction implements Action{
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("productType"));
Product product = Product.builder()
.name(request.getParameter("productName"))
.type(ProductType.valueOf(request.getParameter("productType")))
.price(Integer.parseInt(request.getParameter("productPrice")))
.count(Integer.parseInt(request.getParameter("productCount")))
.build();
ProductRepository productRepository = ProductRepository.getInstance();
int result = productRepository.insertItem(product);
if(result ==1 ) {
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
}
}
ProductRepository
package com.jaybon.product.repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.jaybon.product.db.DBConn;
import com.jaybon.product.model.Product;
import com.jaybon.product.model.ProductType;
public class ProductRepository {
private static final String TAG = "ProductRepository : "; // TAG 생성 (오류 발견시 용이)
private static ProductRepository instance = new ProductRepository();
private ProductRepository() {
}
public static ProductRepository getInstance() {
return instance;
}
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
public int insertItem(Product product) { // object 받기(안에 내용 다 받아야 하니까)
final String SQL = "INSERT INTO product(id, name, type, price, count) "
+ "VALUES(PRODUCT_SEQ.nextval,?,?,?,?)";
try {
conn = DBConn.getConnection(); // DB에 연결
pstmt = conn.prepareStatement(SQL);
pstmt.setString(1, product.getName());
pstmt.setString(2, product.getType().toString());
pstmt.setInt(3, product.getPrice());
pstmt.setInt(4, product.getCount());
return pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
System.out.println(TAG + "insertItem : " + e.getMessage());
} finally {
DBConn.close(conn, pstmt, rs);
}
return -1; // 실패시
}
public int deleteById(int id) {
final String SQL = "DELETE FROM product WHERE id =?";
List<Product> products = null;
try {
conn = DBConn.getConnection(); // DB에 연결
pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1, id);
int result = pstmt.executeUpdate();
return result;
} catch (SQLException e) {
e.printStackTrace();
System.out.println(TAG + "deleteById : " + e.getMessage());
} finally {
DBConn.close(conn, pstmt, rs);
}
return -1; // 실패시
}
// product 다찾기
public List<Product> findAll() { // object 받기(안에 내용 다 받아야 하니까)
final String SQL = "SELECT id, name, type, price, count FROM product ORDER BY id asc";
List<Product> products = null;
try {
conn = DBConn.getConnection(); // DB에 연결
pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
if(rs.next()) {
products = new ArrayList<>();
Product product = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product);
while (rs.next()) {
Product product1 = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product1);
}
}
return products;
} catch (SQLException e) {
e.printStackTrace();
System.out.println(TAG + "findAll : " + e.getMessage());
} finally {
DBConn.close(conn, pstmt, rs);
}
return null; // 실패시
}
public List<Product> findAllPriceAsc() { // object 받기(안에 내용 다 받아야 하니까)
final String SQL = "SELECT id, name, type, price, count FROM product ORDER BY Price ASC";
List<Product> products = null;
try {
conn = DBConn.getConnection(); // DB에 연결
pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
if(rs.next()) {
products = new ArrayList<>();
Product product = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product);
while (rs.next()) {
Product product1 = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product1);
}
}
return products;
} catch (SQLException e) {
e.printStackTrace();
System.out.println(TAG + "findAll : " + e.getMessage());
} finally {
DBConn.close(conn, pstmt, rs);
}
return null; // 실패시
}
public List<Product> findAllPriceDesc() { // object 받기(안에 내용 다 받아야 하니까)
final String SQL = "SELECT id, name, type, price, count FROM product ORDER BY Price DESC";
List<Product> products = null;
try {
conn = DBConn.getConnection(); // DB에 연결
pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
if(rs.next()) {
products = new ArrayList<>();
Product product = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product);
while (rs.next()) {
Product product1 = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product1);
}
}
return products;
} catch (SQLException e) {
e.printStackTrace();
System.out.println(TAG + "findAll : " + e.getMessage());
} finally {
DBConn.close(conn, pstmt, rs);
}
return null; // 실패시
}
public List<Product> findAllCountDesc() { // object 받기(안에 내용 다 받아야 하니까)
final String SQL = "SELECT id, name, type, price, count FROM product ORDER BY count DESC";
List<Product> products = null;
try {
conn = DBConn.getConnection(); // DB에 연결
pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
if(rs.next()) {
products = new ArrayList<>();
Product product = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product);
while (rs.next()) {
Product product1 = Product.builder()
.id(rs.getInt(1))
.name(rs.getString(2))
.type(ProductType.valueOf(rs.getString(3)))
.price(rs.getInt(4))
.count(rs.getInt(5))
.build();
products.add(product1);
}
}
return products;
} catch (SQLException e) {
e.printStackTrace();
System.out.println(TAG + "findAll : " + e.getMessage());
} finally {
DBConn.close(conn, pstmt, rs);
}
return null; // 실패시
}
}
테스트 결과
'Web > Jsp' 카테고리의 다른 글
야구 선수 게시판 예제 만들기 (5) | 2020.06.16 |
---|---|
이클립스 eclipse sts툴 java / html / javascript / jsp 자동완성 (2) | 2020.06.16 |
블로그 댓글 지우기 (0) | 2020.06.15 |
get / post 방식 (0) | 2020.06.12 |
블로그 댓글쓰기 (0) | 2020.06.12 |