기본 구조 세팅은 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

 

댓글id추가

 

 

내용을 추가해주었으니 댓글을 새로 작성할 때에도 내용을 추가해야한다

replyWrite(boardId, userId)

 

지우기 버튼도 추가

 

 

자바스크립트에서 replyDelete 함수 만들기

 

 

ReplyDeleteProcAction

 

 

ReplyRepository

 

 

결과

'Web > Jsp' 카테고리의 다른 글

이클립스 eclipse sts툴 java / html / javascript / jsp 자동완성  (2) 2020.06.16
product 페이지 예제 만들기  (0) 2020.06.15
get / post 방식  (0) 2020.06.12
블로그 댓글쓰기  (0) 2020.06.12
블로그 댓글보기  (0) 2020.06.12

 

https://materializecss.com/icons.html

 

Icons - Materialize

 

materializecss.com

 

 

 

 

----------------------------------------------------

 

https://www.w3schools.com/icons/tryit.asp?filename=tryicons_bootstrap

 

Tryit Editor v3.6

Bootstrap Icons Some Bootstrap icons: Styled Bootstrap icons (size, color, and shadow):

www.w3schools.com

 

w3schools에서 아이콘을 받아본다

 

nav에 추가

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

 

detail에 추가

 

 

결과

 

 

-------------------------------------

 

 

 

 

 

'Web > Html_Css' 카테고리의 다른 글

그리드 grid 사용법  (0) 2020.06.19
부트스트랩 그리드 배치 쉽게 하는 사이트  (0) 2020.06.16
div // p // span 차이  (0) 2020.06.11
부트스트랩 가로세로 정렬  (0) 2020.06.10
부트스트랩 div 내용 오른쪽 정렬  (0) 2020.06.10

함수형 컴포넌트

 

클래스형 컴포넌트

 

클래스형 컴포넌트와 함수형 컴포넌트의 차이점은

클래스형 컴포넌트의 경우
- state 기능
- 라이프사이클 기능을 사용할 수 있다는 것 
- 임의 메서드를 정의할 수 있다는 것
- render함수 필수 + JSX반환 

함수형 컴포넌트의 경우
- 클래스형자료형보다 선언하기 편하다
- 메모리 자원도 클래스형 컴포넌트보다 덜 사용
- 배포시 파일크기가 작다 (성능과는 관계가 없음)
- state와 라이프사이클 API의 사용이 불가능하다는 점
(리액트 V16.8 업데이트 이후 Hooks라는 기능이 도입되면서 해결)

리액트 공식 매뉴얼에서는 컴포넌트를 새로 작성할 때 함수형 컴포넌트와 Hooks를 사용하도록 권장.

 

'Web > ReactJS' 카테고리의 다른 글

플렉스 기초  (0) 2020.07.09
리액트 화면 출력 개념  (0) 2020.07.08
리액트 컨셉 개념  (0) 2020.07.06
리액트 hello-react 예제 이미지 회전 안될 때 (애니메이션)  (0) 2020.06.14
reactJS 리액트 설치하기  (0) 2020.06.14

 

const는 상수를 의미한다

아래와 같이 값을 변경하려고하면

<script>

    const a = 1;
    a = 2;

    alert(a);


</script>

 

에러가 뜬다

 

아래는 에러가 난 라인이다

 

 

참고사이트

https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion

 

prefers-reduced-motion

The prefers-reduced-motion CSS media feature is used to detect if the user has requested that the system minimize the amount of non-essential motion it uses.

developer.mozilla.org

 

회전 등 웹화면의 애니매이션을 생략없이 실행하는 옵션이다.

 

reduce를 사용하면 화면의 애니매이션이 생략된다.

 

no-preference 일 때

 

reduce 일 때

 

그런데 나의 경우 옵션이 반대로 적용되는 것이었다.

이유를 2시간동안 헤메며 찾아본 결과

 

위의 링크의 설명대로 윈도우 설정의 문제였다.

 

아래의 애니메이션이 [켬]상태가 기본인데 나는 자잘한 효과가 싫어서 끔 상태로 했더니 반대로 적용 된 것이었다.

 

 

'Web > ReactJS' 카테고리의 다른 글

플렉스 기초  (0) 2020.07.09
리액트 화면 출력 개념  (0) 2020.07.08
리액트 컨셉 개념  (0) 2020.07.06
클래스형 컴포넌트와 함수형 컴포넌트의 차이점  (0) 2020.06.15
reactJS 리액트 설치하기  (0) 2020.06.14

환경

windows10

 

목차

1. nodejs  설치

2. yarn 설치

3. vscode 설치 + 플러그인 설치

4. 원하는 디렉토리에서 git으로 리액트 예제파일 다운로드

 

nodejs  설치

 

아래 링크로 가서 윈도우 버전을 다운로드 받자

https://nodejs.org/ko/download/

 

다운로드 | Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

 

 

 

 

다운로드 받고나서 설치

 

 

yarn 설치

npm은 nodejs의 패키지를 관리해주는 도구로 nodejs설치할 때 기본으로 설치된다고 한다.

yarn은 npm을 대체할 수 있는 도구로 npm보다 더 빠르며 효율적인 캐시 시스템과 기타 부가 기능을 제공.

 

아래 링크에서 다운로드 하자

https://classic.yarnpkg.com/en/docs

 

Yarn

Fast, reliable, and secure dependency management.

classic.yarnpkg.com

 

 

Getting Started

 

 

스태이블 버전을 다운로드 하자

 

 

 

 

vscode 설치 + 플러그인 설치

 

https://code.visualstudio.com/

 

Visual Studio Code - Code Editing. Redefined

Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications.  Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.

code.visualstudio.com

 

 

 

 

아래의 플러그인을 설치한다

 

1. ESLint: 자바스크립트 문법 및 코드 스타일을 검사

 

2. Reactjs Code Snippets: 리액트 컴포넌트 및 라이프사이클 함수를 작성할 때 단축 단어를 사용하여 간편하게 코드를 자동으로 생성해 낼 수 있는 코드 스니펫 모음.
검색했을 때 유사한 결과가 여러 개 나올 수 있으니 제작자가 charalampos karypidis인 것을 설치.

 

3. Prettier-Code formatter: 코드 스타일을 자동으로 정리해 주는 도구.

 

 

 

원하는 디렉토리에서 git으로 리액트 예제파일 다운로드

 

예제파일을 받아보자

 

yarn create react-app hello-react

 

엔터를 치면 주르륵 깔린다

 

결과

 

해당폴더에 리액트 예제가 깔렸다

 

vscode에서 열어보자(폴더는 hello-react를 선택하자)

 

vscode에서 터미널을 켜자

 

yarn이 안될 경우 아래를 따라해보고 그래도 안되면 기본 터미널을 git bash로 바꿔보자

stackoverflow.com/questions/43313178/react-native-error-yarn-is-not-recognized-as-an-internal-or-external-command

 

React Native Error - yarn' is not recognized as an internal or external command

I am not able to run the sample react Native AwesomeProject project. Can anyone help? Below is the details. C:\Users\dip\AwesomeProject>react-native run-android 'yarn' is not recognized as an

stackoverflow.com

 

yarn start 입력

 

인터넷 창이 뜨며 해당 화면이 출력되면 성공

 

 

 

전달 가능 방식

get방식 - key:value

post, put, delete방식 - key:value + 텍스트 + json + 영상 이미지 등 byte + 등등등

--------------------------

get방식은 getParameter로 값을 받을 수 있고 버퍼로 받지 못한다

post방식처럼 body에 값을 넣어서 전달하는 경우
getParameter로 값을 받을 수 있고 버퍼로도 받을 수 있다

------------------------------

 

'Web > Jsp' 카테고리의 다른 글

product 페이지 예제 만들기  (0) 2020.06.15
블로그 댓글 지우기  (0) 2020.06.15
블로그 댓글쓰기  (0) 2020.06.12
블로그 댓글보기  (0) 2020.06.12
사진 업로드  (0) 2020.06.11

+ Recent posts