1. 자바

Auto Activation에서

딜레이를 0으로

triggers를 마침표(.)와 모든 영어 소문자를 넣어준다

그리고 엔터를 칠 경우에만 자동완성 해주도록 세팅

 

 

2. HTML

자바와 비슷하게 세팅
(제이쿼리를 사용하려면 $ . 등을 더 추가하고 대문자도 넣고 싶으면 넣어도 된다)

 

 

3. 자바스크립트

위와 같이 세팅해주고

 

마켓에서

Eclipse Enterprise Java Developer Tools

인스톨 해준다.(설치가 완료되고도 오른쪽 하단에 백그라운드로 설치되는 경우가 있다. 기다리자.)

이것만 설치해도 function() 등 기본적인 템플레이트가 뜬다

 

 

 

http://blog.naver.com/njw1204/221654918683

 

이클립스에서 자바스크립트 및 jQuery 자동 완성 사용하기 (Tern Eclipse IDE)

이클립스에서 웹 프론트엔드 개발을 할 때 불편한 점이 몇 개 있는데요.그것 중에 하나가 자바스크립트의 ...

blog.naver.com

위의 링크내용대로tern 도 설치해준다.

github.com/angelozerr/tern.java/releases/download/tern.java-1.2.1/tern.repository-1.2.1.zip

 

 

프로젝트를 Tern Project로 변경한다

 

 

프로젝트 프로퍼티스에서 아래와같이 체크해준다

 

 

툴 프리퍼런스에서 자바스크립트 설정을 추가적으로 해준다 

자바스크립트 자동완성 추천 세팅

 

결과

 

 

tern이 안될 경우 아래 사이트 참고

https://blog.naver.com/sulin00/221733387006

 

이클립스에서 자바스크립트 자동완성 플러그인(무료): Wild Web Developer (구 Tern)

이클립스에서 자바스크립트 자동완성 기능 사용하기. --------------------------------------------- 결론...

blog.naver.com

 

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

카카오 로그인 api  (0) 2020.06.17
야구 선수 게시판 예제 만들기  (5) 2020.06.16
product 페이지 예제 만들기  (0) 2020.06.15
블로그 댓글 지우기  (0) 2020.06.15
get / post 방식  (0) 2020.06.12

 

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

 

에러가 뜬다

 

아래는 에러가 난 라인이다

 

 

format on save

'낙서장' 카테고리의 다른 글

200617  (0) 2020.06.17
웹에디터 ckeditor  (0) 2020.06.16
공부할거  (0) 2020.06.13
vsCode 저장시 자동 정렬되게 하기  (0) 2020.06.13
200612  (0) 2020.06.12

 

참고사이트

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

+ Recent posts