gi_dor

게시판 - 삭제 remove() // 공지사항 글 삭제 본문

First/Spring

게시판 - 삭제 remove() // 공지사항 글 삭제

기돌 2023. 7. 18. 21:23
728x90
1. DB 테이블
2. DTO
3. Mapper
4. DAO
5. Service
6.Controller
7. View  / jsp 파일

공지 사항에 있는 글 삭제 하기 !


DB


DTO

public class NoticeDTO {

    private Integer notcNo;
    private String notcTp;
    private String title;
    private String content;
    private Integer viewCnt;
    private char fixYn;
    private Date startDttm;
    private Date endDttm;
    private Date regDttm;
    private Integer regrId;
    private Date updDttm;
    private Integer updrId;
    private Date delDttm;
    private Integer delrId;
    private char delYn;

	// 공지 사항 글 하단에 다음 글 , 이전글 
    private String prevTitle;
    private String nextTitle;
    private Integer prevNo;
    private Integer nextNo;
    
 //   + getter, setter , toString , eqauls() HashCode() 추가 
 // 	Mapper 에 맞게 생성자 , 기본 생성자 , 전체 생성자
    
}

Mapper

<!--    공지사항 전체 삭제-->
    <delete id="deleteAll">
        DELETE
        FROM notice
    </delete>

<!--    공지사항 1개 삭제-->
    <delete id="delete" parameterType="int">
        delete
        from notice
        where NOTC_NO = #{notcNo}
    </delete>



    <!--    모든 공지사항 내용 조회-->
    <!-- 삭제 여부(DEL_YN)가 'N'인 공지사항의 모든 정보를 조회하고,
    등록일자(REG_DTTM)와 공지사항 번호(NOTC_NO)로 내림차순 정렬하는 쿼리 -->
    <select id="selectAll" resultType="NoticeDTO">
        SELECT NOTC_NO, NOTC_TP, TITLE, CONTENT, REGR_ID, VIEW_CNT, REG_DTTM , UPD_DTTM , START_DTTM ,END_DTTM
        FROM notice
        where DEL_YN = 'N'
        ORDER BY REG_DTTM DESC, NOTC_NO DESC
    </select>

 

 


DAO

public interface NoticeDAO {	

	int delete(Integer notcNo) throws Exception;
    
    }
@Repository
public class NoticeDAOImpl implements NoticeDAO {
    @Autowired
    SqlSession session;

    String namespace = "aaa.asdfghjkl.asd.NoticeMapper.";
    
        @Override
    public int delete(Integer notcNo) throws Exception{
        return session.delete(namespace+"delete",notcNo);
    	}
    }


Service

public interface NoticeService {
   int remove(Integer notcNo) throws Exception;
}
@Service
public class NoticeServiceImpl implements NoticeService {

    // DAO 주입시 생성자로 주입 받기!!!
    NoticeDAO noticeDao;
    
    
    @Autowired
    public NoticeServiceImpl(NoticeDAO noticeDao) {
        this.noticeDao = noticeDao;
    }


    @Override
    public int remove(Integer notcNo) throws Exception {
        return noticeDao.delete(notcNo);
   		 }
    
    }

 



Controller

@Controller
@RequestMapping("/adminNotice")
public class AdminNoticeController {

    @Autowired
    NoticeService noticeService;

    @PostMapping("remove")
    public String remove(Integer notcNo ,SearchCondition sc , Model m , HttpSession session , RedirectAttributes rattr ){
//                                                        ,@SessionAttribute Integer mbrId ,@SessionAttribute String lginId
        try{
            m.addAttribute("sc",sc);
            System.out.println("notcNo = " + notcNo);

            int rowCnt =  noticeService.remove(notcNo);

            if (rowCnt != 1) {  // 삭제된 행이 1이 아니라면
                // 실패 에러 메세지 발생
                throw new Exception("adminNotice remove error");
            }

                // 삭제된 행이 1이라면
                // 성공 메세지
                rattr.addFlashAttribute("msg", "DEL_OK");
        } catch (Exception e) {
            e.printStackTrace();
            rattr.addFlashAttribute("msg","DEL_ERR");
        }

        return "redirect:/adminNotice/list";
    	}
    
    }

사실 HttpSession은 제외해도 된다.

원래는 작성자가 해당글만 삭제 할수 있게 해야하는데
일단 로그인 체크 없이 삭제 하려고 만듬 



View  / jsp 파일

 <form id="form" class="frm" action="" method="post">
        <div class="notice-list">공지 사항 목록
            <%--    게시글 갯수 카운팅--%>
            <span class="notice_count">
                (총 ${ph.totalCnt}개)
            </span>
        </div>

        <table class="table table-hover">

            <tr class="table-dark">
                <th scope="col">번호</th>
                <th scope="col">공지사항 분류 코드</th>
                <th scope="col">제목</th>
                <th scope="col">조회수</th>
                <th scope="col">등록 일자</th>
                <th scope="col">공지 시작</th>
                <th scope="col">공지 종료</th>
                <th scope="col"> 수정 </th>
                <th scope="col"> 삭제 </th>

            </tr>

            <c:forEach var="noticeDTO" items="${list}">
             <%--   <input type="hidden" name="notcNo" value="${noticeDTO.notcNo}">--%>
                <tr class="table-light">
                    <td scope="row">${noticeDTO.notcNo}</td>        <%---공지사항 번호---%>
                    <td><c:out value="${noticeDTO.notcTp}"/></td>   <%---공지사항 타입---%>
                    <td><a href = "<c:url value="/adminNotice/read${ph.sc.queryString}&notcNo=${noticeDTO.notcNo}"/>"> ${noticeDTO.title}</a></td> <%---공지사항 제목---%>
                        <%--                    <a href = "<c:url value='/adminNotice/read?notcNo=${noticeDTO.notcNo}&page=${page}&pageSize=${pageSize}'/>">${noticeDTO.title}</a>--%>
                    <td>${noticeDTO.viewCnt}</td>                   <%---공지사항 조회수---%>

					td><button type="button" id="modifyBtn" class="modifyBtn">수정</button></td>
                    <td><button type="button" id="removeBtn" class="removeBtn">삭제</button></td>
                </tr>
            </c:forEach>


        </table>
</form>

 

<script>
    $(document).ready(function (){

        $('.removeBtn').on("click", function(){
            if(!confirm("삭제 하시겠습니까 ?")) return;
            let form =  $('#form');
            let url =  "<c:url value='/adminNotice/remove${searchCondition.queryString}'/>";
            form.attr("action", url);
            form.attr("method", "post");
            form.submit();
        });

    });
</script>

솔직히 JS도 모르고 aJax ? 이런거 모른다!

 

 


 

 

notcNo = null ?  어디갔어


 

주의 !!!!

컨트롤러에 remove() 메서드의 매개변수로 Integer notcNo가 있으므로, 클라이언트 측에서 해당 값을 전송해야 한다
만약 <form id="form" class="frm" action="" method="post">  폼태그로 전송하게 된다면

input 태그로 notcNo값을 전송 해줘야한다.


 

 <input type="hidden" name="notcNo" value="${noticeDTO.notcNo}">

 

<input> 태그에 hidden을  ?
▶ 굳이 공지사항 글의 번호를 보여줄 필요는 없어서 hidden으로 숨김 처리를 했다
▶ 왜 input 태그 ? <input type="text"><textarea><select> 태그로도  데이터로도 전송 할수 있다고 하는데
    내가 아는 건 <input> 태그 뿐이라서..

 

remove()  메서드의 매개변수로 
Integer notcNo 있는데  스프링 MVC는 요청 파라미터 중에서  notcNo랑 일치하는 값을 찾아서 
notcNo 매개변수에 자동으로 바인딩 된다

클라이언트에서 notcNo값을 전송하면 해당값이 notcNo 매개변수로 자동으로 설정된다

 


 

 

 

찾았다 내 notcNo

728x90