⁂ MyBatis Framework/: 기본 익히기

[MyBatis3] #4-7 파일 업로드 및 댓글 게시판 만들기 : 삭제 기능 넣기

김갱환 2022. 11. 11. 16:49

 

1. Model

 * 짚고 넘어갈 뽀인트

-  컨트롤러에서 기존의 파일 이름을 가져오기 위해 두 가지의 Model 접근 코드가 존재.

 

1) product.xml

<select id="filename" resultType="String">
    <![CDATA[
    SELECT filename
    FROM product
    WHERE product_code = #{product_code}
    ]]>
</select>

<delete id="delete">
    <![CDATA[
    DELETE FROM product
    WHERE product_code = #{product_code}
    ]]>
</delete>

 

2) productDAO.java

public String filename(int product_code) {
    return sqlSession.selectOne("product.filename", product_code);
} // filename() end

public void delete(int product_code) {
    sqlSession.delete("product.delete", product_code);
} // delete() end

 

 

2. View

 * 짚고 넘어갈 뽀인트

- 상품 삭제 버튼을 클릭할 시 product_delete() function 호출.

- document.form1.action 을 활용하여 액션을 취한다.

 : 이는 <form action="/product/delete">와 같은 기능이다. 즉, 한 폼 안에서 다양한 액션을 취할 수 있다.

 

<input type="button" value="상품삭제" onclick="product_delete()">
function product_delete(){
    if(confirm("영구히 삭제됩니다\n진행할까요?")){
        document.form1.action="/product/delete";
        document.form1.submit();
    }// if end
} // product_delete() end

 

 

3. Controller

 * 짚고 넘어갈 뽀인트

- delete 명령어 생성

- DAO의 filename() 메서드와 delete() 메서드를 호출.

 

@RequestMapping("/delete")
public String delete(int product_code, HttpServletRequest req) {
    String filename = productDao.filename(product_code);
    if(filename != null && !filename.equals("-")) {
        ServletContext application = req.getSession().getServletContext();
        String path = application.getRealPath("/storage");
        File file = new File(path+"\\"+filename);
        if(file.exists()) {
            file.delete();
        } // if end
    } // if end
    productDao.delete(product_code); // 행삭제

    return "redirect:/product/list";
} // delete() end