Server

AJAX STEP 9 - 상품 목록 페이지

2023. 5. 17. 17:45
728x90

★ 상품 목록 페이지

 

■ 필요 파일

com.test.java > Ex13.java
com.test.java > Ex13Add.java
com.test.java > Ex13Del.java
com.test.java > Ex13DTO.java
com.test.java > Ex13Edit.java

views > ex13.jsp

 

■ 데이터베이스

create table tblProduct (
    seq number primary key,                 -- 번호(PK)
    name varchar2(100) not null,            -- 상품명
    price number not null,                      -- 가격
    color varchar2(50) not null,                 -- 색상
    pic varchar2(100) default 'pic.png' not null -- 사진
);

create sequence seqProduct;

 

■ 소스코드

  • Ex13.java
package com.test.ajax;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ex13.do")
public class Ex13 extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		//Ex13.java
		
		AjaxDAO dao = new AjaxDAO();
		
		List<Ex13DTO> list = dao.listProduct();
		
		req.setAttribute("list", list);

		RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/ex13.jsp");
		dispatcher.forward(req, resp);
	}

}

 

  • Ex13Add.java
package com.test.ajax;

import java.io.IOException;
import java.io.PrintWriter;

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 org.json.simple.JSONObject;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

@WebServlet("/ex13add.do")
public class Ex13Add extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		//Ex13Add.java
		
		try {
			
			//System.out.println(req.getRealPath("/pic"));
			
			MultipartRequest multi = new MultipartRequest(
										req,
										req.getRealPath("/pic"),
										1024 * 1024 * 100,
										"UTF-8",
										new DefaultFileRenamePolicy()
									);
					
			
			String name = multi.getParameter("name");
			String price = multi.getParameter("price");
			String color = multi.getParameter("color");
			String pic = multi.getFilesystemName("pic");
			
			Ex13DTO dto = new Ex13DTO();
			
			dto.setName(name);
			dto.setPrice(price);
			dto.setColor(color);
			dto.setPic(pic);
			
			AjaxDAO dao = new AjaxDAO();
			
			int result = dao.addProduct(dto);
			
			//방금 등록한 상품 가져오기
			Ex13DTO newProduct = dao.getProduct();
			
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/json");
			
			PrintWriter writer = resp.getWriter();
			//writer.printf("{ \"result\": %d }", result);
			
			JSONObject obj = new JSONObject();
			obj.put("result", result);
			obj.put("pic", newProduct.getPic());
			obj.put("seq", newProduct.getSeq());
			
			writer.print(obj);
			
			writer.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		
		
		
	}

}

 

  • Ex13Del.java
package com.test.ajax;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

@WebServlet("/ex13del.do")
public class Ex13Del extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		//Ex13Del.java
		String seq = req.getParameter("seq");
		
		AjaxDAO dao = new AjaxDAO();
		
		int result = dao.delProduct(seq);
		
		JSONObject obj = new JSONObject();
		obj.put("result", result);
		
		resp.setContentType("application/json");
		
		PrintWriter writer = resp.getWriter();
		writer.print(obj);
		writer.close();
		
	}

}

 

  • Ex13Edit.java
package com.test.ajax;

import java.io.IOException;
import java.io.PrintWriter;

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 org.json.simple.JSONObject;

@WebServlet("/ex13edit.do")
public class Ex13Edit extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		//Ex13Edit.java
		String seq = req.getParameter("seq");
		String name = req.getParameter("name");
		String price = req.getParameter("price");
		String color = req.getParameter("color");
		
		AjaxDAO dao = new AjaxDAO();
		
		Ex13DTO dto = new Ex13DTO();
		
		dto.setSeq(seq);
		dto.setName(name);
		dto.setPrice(price);
		dto.setColor(color);
		
		int result = dao.editProduct(dto);
		
		resp.setContentType("application/json");
		
		PrintWriter writer = resp.getWriter();
		
		JSONObject obj = new JSONObject();
		obj.put("result", result);
		
		writer.print(obj);
		writer.close();
		
		
	}

}

 

  • Ex13DTO.java
package com.test.ajax;

import lombok.Data;

@Data
public class Ex13DTO {
	private String seq;
	private String name;
	private String price;
	private String color;
	private String pic;
}

 

  • DAO
public int addProduct(Ex13DTO dto) {

    try {

        String sql = "insert into tblProduct (seq, name, price, color, pic) values (seqProduct.nextVal, ?, ?, ?, ?)";

        pstat = conn.prepareStatement(sql);
        pstat.setString(1, dto.getName());
        pstat.setString(2, dto.getPrice());
        pstat.setString(3, dto.getColor());
        pstat.setString(4, dto.getPic());

        return pstat.executeUpdate();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return 0;
}

public List<Ex13DTO> listProduct() {

      try {

         String sql = "select * from tblProduct order by seq desc";

         stat = conn.createStatement();
         rs = stat.executeQuery(sql);

         List<Ex13DTO> list = new ArrayList<Ex13DTO>();

         while (rs.next()) {

            Ex13DTO dto = new Ex13DTO();

            dto.setSeq(rs.getString("seq"));
            dto.setName(rs.getString("name"));
            dto.setPrice(rs.getString("price"));
            dto.setColor(rs.getString("color"));
            dto.setPic(rs.getString("pic"));

            list.add(dto);

         }

         return list;

      } catch (Exception e) {
         e.printStackTrace();
      }

      return null;
   }

public Ex13DTO getProduct() {

    try {

        String sql = "select seq, pic from tblProduct"
                + " where seq = (select max(seq) from tblProduct)";

        stat = conn.createStatement();
        rs = stat.executeQuery(sql);

        if (rs.next()) {
            Ex13DTO dto = new Ex13DTO();

            dto.setSeq(rs.getString("seq"));
            dto.setSeq(rs.getString("pic"));

            return dto;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

public int delProduct(String seq) {

    try {

        String sql = "delete from tblProduct where seq = ?";

        pstat = conn.prepareStatement(sql);
        pstat.setString(1, seq);

        return pstat.executeUpdate();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return 0;
}

public int editProduct(Ex13DTO dto) {

    try {

        String sql = "update tblProduct set name = ?, price = ?, color = ? where seq = ?";

        pstat= conn.prepareStatement(sql);
        pstat.setString(1, dto.getName());
        pstat.setString(2, dto.getPrice());
        pstat.setString(3, dto.getColor());
        pstat.setString(4, dto.getSeq());

        return pstat.executeUpdate();


    } catch (Exception e) {
        e.printStackTrace();
    }

    return 0;
}

 

  • ex13.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
   #list {
      
   }
   
   #list th:nth-child(1) { width: 160px; }
   #list th:nth-child(2) { width: 240px; }
   #list th:nth-child(3) { width: 110px; }
   #list th:nth-child(4) { width: 100px; }
   #list th:nth-child(5) { width: 158px; }
   
   #list td:nth-child(1) img { width: 150px; height: 150px; object-fit: cover; }
   #list td { text-align: center; }
   
</style>
</head>
<body>
   <!-- ex13.jsp -->
   
   <h1>Product List</h1>
   
   <table id="list">
      <thead>
         <tr>
            <th>사진</th>
            <th>제품명</th>
            <th>가격</th>
            <th>색상</th>
            <th>편집</th>
         </tr>
      </thead>
      <tbody>
         <c:forEach items="${list}" var="dto">
         <tr>
            <td><img src="/ajax/pic/${dto.pic}"></td>
            <td>${dto.name}</td>
            <td><fmt:formatNumber value="${dto.price}" />원</td>
            <td>${dto.color}</td>
            <td>
               <div>
                  <input type="button" value="수정" onclick="edit();">
                  <input type="button" value="삭제" onclick="del(${dto.seq});">
               </div>
               <div style="display:none;">
                  <input type="button" value="확인" onclick="editok(${dto.seq});">
                  <input type="button" value="취소" onclick="cancel();">
               </div>
            </td>
         </tr>
         </c:forEach>
      </tbody>
   </table>
   
   <hr>
   
   <form id="form1">
   <table id="add">
      <tr>
         <th>제품명</th>
         <td><input type="text" name="name" id="name"></td>
      </tr>
      <tr>
         <th>가격</th>
         <td><input type="number" name="price" id="price" min="0" max="10000000" step="1000"></td>
      </tr>
      <tr>
         <th>색상</th>
         <td>
            <select name="color" id="color">
               <option value="검정색">검정색</option>
               <option value="흰색">흰색</option>
               <option value="회색">회색</option>
            </select>
         </td>
      </tr>
      <tr>
         <th>사진</th>
         <td><input type="file" name="pic"></td>
      </tr>
   </table>
   </form>
   
   <div>
      <input type="button" value="상품 등록하기" id="btn">
   </div>
   

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
   
   $('#btn').click(()=>{
      
      //일반 텍스트 + 첨부 파일 > Ajax 통해서 전송
      const formData = new FormData(document.getElementById('form1'));
            
      $.ajax({
         
         type: 'POST',
         url: '/ajax/ex13add.do',
         
         enctype: 'multipart/form-data',
         processData: false,
         contentType: false,
         
         data: formData,
         dataType: 'json',
         success: (result)=>{
            
            //alert(result.result);
            if (result.result == 1) {
               
               //테이블에 상품을 추가하기(출력)
               let tr = `
               
                  <tr>
                     <td><img src="/ajax/pic/\${result.pic}"></td>
                     <td>\${$('#name').val()}</td>
                     <td>\${parseInt($('#price').val()).toLocaleString()}원</td>
                     <td>\${$('#color').val()}</td>
                     <td>
                        
                        <div>
                        <input type="button" value="수정" onclick="edit();">
                        <input type="button" value="삭제" onclick="del(\${result.seq});">
	                     </div>
	                     <div style="display:none;">
	                        <input type="button" value="확인" onclick="editok(\${result.seq});">
	                        <input type="button" value="취소" onclick="cancel();">
	                     </div>
	                     
                     </td>
                  </tr>
               
               `;
               
               $('#list tbody').prepend(tr);
               
               $('#name').val('');
               $('#price').val('');
               $('#color').val('검정색');
               
               
            } else {
               alert('failed');
            }
            
         },
         error: (a,b,c)=>console.log(a,b,c)
         
      });
      
   });
   
   let temp_name = '';
   let temp_price = '';
   let temp_color = '';
   
   function edit() {
      
      let tr = event.target.parentElement.parentElement.parentElement;
      
      let name = $(tr).children().eq(1).text();
      $(tr).children().eq(1).html('<input type="text" class="short" value="' + name + '">');
      
      let price = $(tr).children().eq(2).text();
      $(tr).children().eq(2).html('<input type="number" class="short" value="' + price.replace('원', '').replace(/,/g, '') + '" min="0" max="10000000" step="1000">');
      
      let color = $(tr).children().eq(3).text();
      $(tr).children().eq(3).html(
            `
               <select name="color" id="color2">
                  <option value="검정색">검정색</option>
                  <option value="흰색">흰색</option>
                  <option value="회색">회색</option>
               </select>
            `   
      );
      
      $('#color2').val(color);
      
      
      
      $(event.target).parent().parent().children().last().show();
      $(event.target).parent().hide();
      
      temp_name = name;
      temp_price = price;
      tmep_color = color;
      
   }
   
   function del(seq) {
      
      let tr = event.target.parentElement.parentElement.parentElement; //<tr>
      
      $.ajax({
         type: 'POST',
         url: '/ajax/ex13del.do',
         data: {
            seq: seq
         },
         dataType: 'json',
         success: (result)=>{
            
            if (result.result == 1) {
               
               //화면에 있는 상품 안보이게 처리
               $(tr).remove();
               
            } else {
               alert('failed');
            }
            
         },
         error: (a,b,c)=>console.log(a,b,c)
         
      });
      
   }
   
   
   function editok(seq) {
      
	   let name = $(event.target).parent().parent().parent().children().eq(1).children().eq(0).val();
	   let price = $(event.target).parent().parent().parent().children().eq(2).children().eq(0).val();
	   let color = $(event.target).parent().parent().parent().children().eq(3).children().eq(0).val();
	   
	   const btn = event.target;
	   
	   $.ajax({
		  type: 'POST',
		  url: '/ajax/ex13edit.do',
		  data: {
			  seq: seq,
			  name: name,
			  price: price,
			  color: color
		  },
		  dataType: 'json',
		  success: (result)=>{
			 
			  $(btn).parent().hide();
		      $(btn).parent().parent().children().first().show();
		      
		      //제품명
		      let name = $(btn).parent().parent().parent().children().eq(1).children().eq(0).val();
		      //alert(name);
		      $(btn).parent().parent().parent().children().eq(1).text(name);   
		      
		      //가격
		      let price = $(btn).parent().parent().parent().children().eq(2).children().eq(0).val();
		      $(btn).parent().parent().parent().children().eq(2).text(price);   
		      
		      //색상
			  let color = $(btn).parent().parent().parent().children().eq(3).children().eq(0).val();
		      $(btn).parent().parent().parent().children().eq(3).text(color);   
			  
			  
		  },
		  error: (a,b,c)=>console.log(a,b,c)
	   });
	   
   }
   
   function cancel() {
      
      $(event.target).parent().hide();
      $(event.target).parent().parent().children().first().show();
      
      //제품명
      //alert(name);
      $(event.target).parent().parent().parent().children().eq(1).text(temp_name);   
      
      //가격
      $(event.target).parent().parent().parent().children().eq(2).text(temp_price);   
      
      //색상
	  $(event.target).parent().parent().parent().children().eq(3).text(tmep_color);   
      
   }
   
</script>
</body>
</html>

 

■ 실행 결과

상품 페이지
상품 등록

 

728x90
저작자표시 비영리 변경금지 (새창열림)

'Server' 카테고리의 다른 글

AJAX STEP 11 - Map  (0) 2023.05.18
AJAX STEP 10 - 게시판 목록 보기  (0) 2023.05.18
AJAX STEP 8 - 일기장 AJAX  (0) 2023.05.17
AJAX STEP 7 - 테이블 저장 AJAX  (0) 2023.05.17
AJAX STEP 6 - 다양한 전송 방법  (2) 2023.05.17
'Server' 카테고리의 다른 글
  • AJAX STEP 11 - Map
  • AJAX STEP 10 - 게시판 목록 보기
  • AJAX STEP 8 - 일기장 AJAX
  • AJAX STEP 7 - 테이블 저장 AJAX
IT의 큰손
IT의 큰손
IT계의 큰손이 되고 싶은 개린이의 Log 일지
Developer Story HouseIT계의 큰손이 되고 싶은 개린이의 Log 일지
IT의 큰손
Developer Story House
IT의 큰손
전체
오늘
어제
  • 분류 전체보기 (457)
    • 정보처리기사 필기 (18)
    • 정보처리기사 실기 (12)
    • 정보처리기사 통합 QUIZ (12)
    • 빅데이터 (11)
    • 안드로이드 (11)
    • 웹페이지 (108)
    • 자바 (49)
    • SQLD (3)
    • 백준 알고리즘 (76)
    • 데이터베이스 (41)
    • 깃허브 (2)
    • Library (14)
    • Server (31)
    • 크롤링&스크래핑 (3)
    • Spring (23)
    • Vue.js (13)
    • React (27)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Developer Stroy House

인기 글

태그

  • 백준
  • ajax
  • 코딩테스트
  • IT개발자
  • 데이터베이스
  • html
  • DBA
  • 개발자
  • 정보처리기사
  • 개발블로그
  • IT자격증공부
  • jquery
  • css
  • JavaScript
  • jsp
  • 앱개발자
  • 알고리즘
  • 웹개발
  • IT자격증
  • DB
  • React
  • 백엔드
  • 자바
  • 웹페이지
  • 웹개발자
  • it
  • java
  • 정보보안전문가
  • 프론트엔드
  • 정보처리기사필기

최근 댓글

최근 글

Designed By hELLO
IT의 큰손
AJAX STEP 9 - 상품 목록 페이지
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.