본문 바로가기
JSP

JSP(상품재고관리 프로그램)_2024-09-04

by 앵보몬 2024. 9. 5.
728x90
반응형

이 JSP 페이지는 상품 정보를 조회하고, 상품을 추가하기 위한 폼을 제공하는 내용을 담고 있습니다. 코드의 주요 기능과 수정할 점은 다음과 같습니다.

주요 기능
① 상품 정보 조회 : 데이터베이스에서 상품 정보를 조회하고 이를 HTML 테이블에 출력합니다.

② 상품 추가 폼 : 상품 정보를 입력할 수 있는 폼을 제공합니다. 이 폼은 GET 메서드를 사용하여 데이터를 전송합니다.  

 

개선 사항 및 주의사항

① JSP에서 Java 코드 최소화 : JSP 페이지에서 Java 코드를 직접 사용하는 것은 유지보수와 테스트를 어렵게 만들 수 있습니다. 가능한 경우 JSP는 HTML과 JSTL 또는 EL(Expression Language)만 사용하는 것이 좋습니다. 비즈니스 로직은 서블릿이나 서비스 클래스로 분리하는 것이 좋습니다.

② 데이터베이스 연결 관리 : JDBConnect 클래스에서 데이터베이스 연결과 쿼리 실행을 직접 처리하는 것은 좋지 않습니다. 데이터베이스 연결은 커넥 션 풀을 사용하는 것이 좋습니다. 또한, JDBConnect 클래스가 Statement와 Connection 객체를 직접 다루는 것도 지양해 야 합니다.

③ 문자 인코딩 : EUC-KR 대신 UTF-8을 사용하는 것이 더 범용적이고 표준입니다. EUC-KR은 특정 지역에서만 사용되며, UTF-8은 다양한 언어를 지원합니다.

④ 폼 액션 및 경로 : 폼의 action 속성이 "/JSP/products"로 되어 있는데, 이 경로가 실제로 존재하는지 확인하세요. 이 경로는 JSP 페이지가 있는 경로인지 확인할 필요가 있습니다. 또한, 상품 추가 폼의 경우, POST 메서드를 사용하는 것이 좋습니다. GET 메서드는 URL에 데이터가 노출되므로 보안상 안전하지 않습니다.

⑤ 리소스 누수 방지 : 데이터베이스 연결과 같은 리소스는 finally 블록에서 닫아야 합니다. rs와 jdbc.con을 닫는 코드가 있지만, jdbc.stmt도 닫는 것이 좋습니다.

 

 

main.jsp
0.00MB
delete.java
0.00MB
products.java
0.00MB
update.java
0.00MB
insert.java
0.00MB

 

DB

create table products (
    product_id number(4) primary key,
    product_name varchar2(20) not null,
    category varchar2(20),
    price number(10, 2),
    description varchar2(20),
    stock_quantity number(10, 2)
    );
   
insert into products values (1, '아이폰 15', '스마트폰', 1500000, '최신 스마트폰', 52000);
insert into products values (2, '삼성 갤럭시 s24', '스마트폰', 1400000, '고성능 스마트폰', 62000);
insert into products values (3, '맥북 프로 14', '노트북', 2500000, '고급형 노트북', 52000);
insert into products values (4, '삼성 노트북', '노트북', 1800000, '가성비 노트북', 62000);
insert into products values (5, '에어팟 프로 2세대', '이어폰', 350000, '무선 노이즈캔슬링 이어폰', 62000);
COMMIT;

select * from products;

 

main.jsp

<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="common.JDBConnect"%>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>  
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="EUC-KR" />
    <title>상품재고관리</title>
  </head>
  <body>
    <h2>상품정보</h2>
    <hr>
    <form action="/JSP/products" method="get"><button type="submit">새로고침</button></form>
    <table border="1">
       <tr>
         <th>상품아이디</th>
         <th>상품명</th>
         <th>카테고리</th>
         <th>가격</th>
         <th>비고</th>
         <th>재고수량</th>
         <th>삭제</th>
         <th>수정</th>
       </tr>
   <c:forEach items="${products}" var="products">
      <tr>
         <td>${products[0]}</td>
         <td>${products[1]}</td>
         <td>${products[2]}</td>
         <td>${products[3]}</td>
         <td>${products[4]}</td>
         <td>${products[5]}</td>
         <td><button onclick="deleteProduct(${products[0]})">삭제</button></td>
          <td><button type="button" onclick="modifyProduct('${products[0]}', '${products[1]}', '${products[2]}', '${products[3]}', '${products[4]}', '${products[5]}')">수정</button></td>
      </tr>  
   </c:forEach>
   </table>
    <h2>상품추가 및 수정</h2>
    <hr>
    <form method="post" action="/JSP/insert">
       <label>아이디:</label>
       <input type="text" name="product_id"><br>
       <label>상품명:</label>
       <input type="text" name="product_name"><br>
       <label>카테고리:</label>
       <input type="text" name="category"><br>
       <label>가격:</label>
       <input type="text" name="price"><br>
       <label>비고:</label>
       <input type="text" name="description"><br>
       <label>재고:</label>
       <input type="text" name="stock_quantity"><br>
       <input type="submit" value="등록">
       <%-- <button type="button" onclick="updateProduct();">수정</button> --%>
       <input type="submit" onclick="updateProduct()" value="수정">
    </form>
       
    <script>
    function deleteProduct(product_id) {
        if (confirm("정말 삭제하시겠습니까?")) {
            var form = document.createElement("form");
            form.method = "POST"
            form.action = "/JSP/delete";
            var input = document.createElement("input");
            input.type = "hidden";
            input.name = "delete_id";
            input.value = product_id;
            form.appendChild(input);
            document.body.appendChild(form);
            form.submit();
        }
    }
   

    function modifyProduct(product_id, product_name, category, price, description, stock_quantity) {
        document.querySelector('input[name="product_id"]').value = product_id;
        document.querySelector('input[name="product_name"]').value = product_name;
        document.querySelector('input[name="category"]').value = category;
        document.querySelector('input[name="price"]').value = price;
        document.querySelector('input[name="description"]').value = description;
        document.querySelector('input[name="stock_quantity"]').value = stock_quantity;
      }
   
         function updateProduct() {
                if (confirm("정말 수정하시겠습니까?")) {
                //<form> 태그의 name 속성으로 <form>태그 객체를 받아온다.
                var myForm = document.myForm;

                //<form>태그 내 <input>태그의 속성으로 입력한 ID와 비밀번호를 받아온다
                var product_id = myForm.product_id.value;
                var product_name = myForm.product_name.value;
                var category = myForm.category.value;
                var price = myForm.price.value;
                var description = myForm.description.value;
                var stock_quantity = myForm.stock_quantity.value;

                myForm.method = "post"; //전송방식 post
                myForm.action = "/JSP/update"; //action 속성을 서블릿 매핑 이름으로
                myForm.submit(); //자바스크립트에서 서블릿으로 전송  
                }        

         }
    </script>
</body>
</html>

 

products.jsp

package common;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

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

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ResultSet rs = null;
        JDBConnect jdbc = new JDBConnect();
   
    try {
        String sql = "select * from products";
        jdbc.stmt = jdbc.con.createStatement();
        rs = jdbc.stmt.executeQuery(sql);
       
        List<String[]> products = new ArrayList<>();
       
        while (rs.next()) {
            String[] product = new String[6];
           
            product[0] = rs.getString("product_id");
            product[1] = rs.getString("product_name");
            product[2] = rs.getString("category");
            product[3] = rs.getString("price");
            product[4] = rs.getString("description");
            product[5] = rs.getString("stock_quantity");
       
            products.add(product);
        }
   
        request.setAttribute("products", products);
        request.getRequestDispatcher("/2024-09-04/main.jsp").forward(request, response);
   
        }catch (SQLException e){
        out.println("데이터베이스 접속오류:" +e.getMessage());
        } finally {
            try {
                if (rs != null) rs.close();
                if (jdbc.con != null) jdbc.con.close();
            }catch (SQLException e){
                out.println("리소스 해제 오류:" +e.getMessage());
            }  
        }
    }

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

}

 

update.java

package common;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class update1
 */
public class update extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public update() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //doGet(request, response);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String product_id = request.getParameter("product_id");
        String product_name = request.getParameter("product_name");
        String category = request.getParameter("category");
        String price = request.getParameter("price");
        String description = request.getParameter("description");
        String stock_quantity = request.getParameter("stock_quantity");

        JDBConnect jdbc = new JDBConnect();
       
        try {
            String sql = "UPDATE products SET product_name = ?, category = ?, price = ?, description = ?, stock_quantity = ? WHERE product_id = ?";
            try (PreparedStatement pstmt = jdbc.con.prepareStatement(sql)) {
                pstmt.setString(1, product_name);
                pstmt.setString(2, category);
                pstmt.setDouble(3, Double.parseDouble(price));
                pstmt.setString(4, description);
                pstmt.setInt(5, Integer.parseInt(stock_quantity));
                pstmt.setString(6, product_id);

                int rowsUpdated = pstmt.executeUpdate();
                if (rowsUpdated > 0) {
                    out.println("수정완료");
                } else {
                    out.println("실패");
                }
                out.println("<br>");
                out.println("<a href=\"javascript:history.back()\">Go back</a>");
            }
        } catch (NumberFormatException e) {
            out.println("Invalid number format: " + e.getMessage());
        } catch (SQLException e) {
            out.println("Database access error: " + e.getMessage());
        } finally {
            try {
                if (jdbc.con != null) jdbc.con.close();
            } catch (SQLException e) {
                out.println("Error closing resources: " + e.getMessage());
            }
        }
    }
}

 

update.java

package common;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class update1
 */
public class update extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public update() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //doGet(request, response);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String product_id = request.getParameter("product_id");
        String product_name = request.getParameter("product_name");
        String category = request.getParameter("category");
        String price = request.getParameter("price");
        String description = request.getParameter("description");
        String stock_quantity = request.getParameter("stock_quantity");

        JDBConnect jdbc = new JDBConnect();
       
        try {
            String sql = "UPDATE products SET product_name = ?, category = ?, price = ?, description = ?, stock_quantity = ? WHERE product_id = ?";
            try (PreparedStatement pstmt = jdbc.con.prepareStatement(sql)) {
                pstmt.setString(1, product_name);
                pstmt.setString(2, category);
                pstmt.setDouble(3, Double.parseDouble(price));
                pstmt.setString(4, description);
                pstmt.setInt(5, Integer.parseInt(stock_quantity));
                pstmt.setString(6, product_id);

                int rowsUpdated = pstmt.executeUpdate();
                if (rowsUpdated > 0) {
                    out.println("수정완료");
                } else {
                    out.println("실패");
                }
                out.println("<br>");
                out.println("<a href=\"javascript:history.back()\">Go back</a>");
            }
        } catch (NumberFormatException e) {
            out.println("Invalid number format: " + e.getMessage());
        } catch (SQLException e) {
            out.println("Database access error: " + e.getMessage());
        } finally {
            try {
                if (jdbc.con != null) jdbc.con.close();
            } catch (SQLException e) {
                out.println("Error closing resources: " + e.getMessage());
            }
        }
    }
}

 

delete.java

package common;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        PreparedStatement pstmt;
        ResultSet rs = null;
        JDBConnect jdbc = new JDBConnect();
       
        try {
            String sql = "delete from products where product_id = ?";
            pstmt = jdbc.con.prepareStatement(sql);
            String delete_id = request.getParameter("delete_id");
            pstmt.setString(1, delete_id);

            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println(rowsAffected);
                out.println("<script>");
                out.println("alert('상품 삭제 성공');");
                out.println("location.href ='2024-09-04/main.jsp';");
                out.println("</script>");
            }else {
                out.println("<b>상품 삭제 실패</b>");
            }
           
        } catch (SQLException e) {
            out.println("데이터베이스 접속 오류: " + e.getMessage());
        } finally {
            try {
                if (rs != null) rs.close();
                if (jdbc.con != null) jdbc.con.close();
            } catch (SQLException e) {
                out.println("리소스 해제 오류: " + e.getMessage());
            }
        }
    }

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

}

 

 

 

 

 

 

 

728x90
반응형