React+Spring Boot

상품 삭제 기능

작성자
vita
작성일
2023-11-19 22:03
조회
344

상품 삭제 기능

상품 삭제의 전반적인 흐름은 아래와 같습니다.

 

1. DetailProduct.js에서 [삭제] 버튼을 누르면 http://localhost/delete 주소를 요청하고 ProductController의 delete() method가 호출됩니다.

2. Controller에서 받은 상품코드를 DAO에 보냅니다.

3. DAO는 mapper에 상품코드를 전달합니다.  delete query가 호출되어 상품코드에 해당하는 레코드가 삭제됩니다.

4. 서버에서 처리가 완료되면 React의 ListProduct.js가 실행되고 최신 상품목록을 받아와서 화면에 출력합니다.

 

 

1. DetailProduct.js (React)

파일 위치: c:/react/frontend/src/components/DetailProduct.js

import React, { useRef, useEffect, useState } from 'react';

import './main.css';

import { useNavigate } from 'react-router-dom';

 

function useFetch(url) {

[생략]

            <tr>

              <td colSpan='2' align='center'>

                <button type='button' onClick={() => {

[생략]

                }>수정</button>

                &nbsp;

                <button type='button' onClick={() => {

                  if (window.confirm('삭제할까요?')) {

                    fetch(`/delete?product_code=${data.product_code}`, { method: 'delete' })

                      .then(() => { navigate('/'); });

                  }

                }

                }>삭제</button>

                &nbsp;

                <button onClick={() => navigate('/')}>목록</button>

              </td>

            </tr>

          </tbody>

        </table>

      </>

    );

  }

};

 

export default DetailProduct;

 

[해설]

 

DetailProduct.js 에서 [삭제] 버튼을 누릅니다.

 

<button type='button' onClick={() => {

 

onClick은 버튼을 누를 때 Javascript 함수를 실행하라는 뜻입니다.

 

if (window.confirm('삭제할까요?')) {

    fetch(`/delete?product_code=${data.product_code}`,

    { method: 'delete' })

    .then(() => { navigate('/'); });

}

 

삭제를 할 때는 사용자의 확인을 받는 것이 좋습니다.  window.confirm() 함수를 사용하면 메시지를 출력하고 사용자가 확인 또는 취소 버튼을 눌러서 다음으로 진행할지의 여부를 결정하게 됩니다.  

 

확인 버튼을 누르면 true, 취소 버튼을 누르면 false로 처리됩니다.

 

 

2. product.xml (Spring Boot)

파일 위치: src/main/resources/mappers/product.xml

<?xml version="1.0" encoding="UTF-8"?>

[생략]

    <update id="update">

        update product

        set product_name=#{product_name},

            price=#{price},

            description=#{description},

            filename=#{filename}

        where product_code=#{product_code}

    </update>

    <delete id="delete">

        delete from product

        where product_code=#{product_code}

    </delete>

    <select id="filename" resultType="String">

        select filename

        from product

        where product_code=#{product_code}

    </select>

</mapper>    


3. ProductDAO.java (Spring Boot)

 

delete() method와 filename() method를 작성합니다.

 

파일위치: src/main/java/com/example/product/ProductDAO.java

[생략]

    public void update(Map<String, Object> map) {

        sqlSession.update("product.update", map);

    }

 

    public void delete(int product_code) {

        sqlSession.delete("product.delete", product_code);

    }

    public String filename(int product_code) {

        return sqlSession.selectOne("product.filename", product_code);

    }

}

 

4. ProductController.java (Spring Boot)

 

아래의 코드 중에서 빨간색으로 표시된 delete() method를 작성하시면 됩니다.

 

파일위치: src/main/java/com/example/product/ProductController.java

[생략]

 

    @RequestMapping("/update")

    public void update(@RequestParam Map<String, Object> map, @RequestParam(required = false) MultipartFile img,

            HttpServletRequest request) {

[생략]

    }

 

    @RequestMapping("/delete")

    public void delete(int product_code, HttpServletRequest request) {

        String filename = productDao.filename(product_code);

        if (filename != null && !filename.equals("-")) {

            ServletContext application = request.getSession().getServletContext();

            String path = application.getRealPath("/static/images/");

            File file = new File(path + filename);

            if (file.exists()) {

                file.delete();

            }

        }

        productDao.delete(product_code);

    }

 

}

 

 

[해설]

 

앞의 DetailProduct.js 에서 삭제 버튼을 누르면 Controller의 delete 액션을 호출하게 됩니다.  http://localhost/delete 형식으로 호출이 됩니다.

 

 

    @RequestMapping("/delete")

    public void delete(int product_code, HttpServletRequest request) {

 

    그러면 Controller의 delete() method가 호출됩니다.  Controller에서는 @RequestMapping으로 url을 연결하게 됩니다.

 

 

이 때 무슨 상품을 삭제할지 상품코드를 전달해야 합니다.

상품코드가 int product_code 변수에 전달됩니다.

 

@RequestMapping("/delete")

public String delete(int product_code, HttpServletRequest request) {

 

Controller의 method에는 같은 이름의 변수가 필요합니다.

 

String filename = productDao.filename(product_code);

 

상품을 삭제할 때 첨부파일이 있다면 첨부파일도 함께 삭제해야 합니다.  상품코드에 해당하는 첨부파일 이름을 조회합니다.

 

    public String filename(int product_code) {

        return sqlSession.selectOne("product.filename", product_code);

    }

 

상품코드가 dao의 filename() method에 전달됩니다.

 

    <select id="filename" resultType="String">

        select filename

        from product

        where product_code=#{product_code}

    </select>

 

dao는 id가 filename인 쿼리를 호출합니다.

상품코드에 해당하는 filename이 있으면 리턴되고 없으면 null이 리턴됩니다.

 

String filename = productDao.filename(product_code);

 

mapper에서 구한 filename이 dao에 전달되고, dao는 Controller에 다시 전달합니다.

 

 

        if (filename != null && !filename.equals("-")) {

 

첨부파일이 null이 아니고 빈값이 아닌지 검사합니다.

 

ServletContext application = request.getSession().getServletContext();

String path=application.getRealPath("/static/images/");

 

웹애플리케이션의 실제 경로를 구합니다.

 

 

            File file = new File(path + filename);

            if (file.exists()) {

                file.delete();

            }

 

파일이 존재하면 파일을 삭제합니다.

        

        productDao.delete(product_code);

 

레코드를 삭제하기 위하여 dao에 상품코드를 보냅니다.

 

dao의 delete() method에 상품코드가 전달됩니다.  Controller, dao, mapper에 데이터가 어떻게 흘러가는지 잘 이해하시는 것이 중요합니다.

 

 

[ProductDAO.java 의 코드]

    public void delete(int product_code) {

      sqlSession.delete("product.delete",product_code);

    }

 

mapper의 id가 delete인 쿼리가 실행됩니다.  레코드가 삭제됩니다.

 

[product.xml의 코드]

    <delete id="delete">

        delete from product

        where product_code=#{product_code}

    </delete>

 

mapper에서 레코드 삭제가 완료된 후 다시 React의 ListProduct.js 로 돌아와서 http://localhost/list 로 이동하여 화면에 반영합니다.

 

5. 상품 삭제 실행 결과 확인

상품 상세 화면에서 [삭제] 버튼을 클릭하면 상품이 삭제됩니다.

 


 

Scroll to Top