Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 단위테스트코드
- 게시판
- 비전공개발자
- React+JPA
- mybatis
- CRUD
- springboot
- @Transactional
- 게시판 CRUD
- I/OStream
- 게시물수정
- 로컬이미지삭제
- Self-invocation
- 로컬이미지불러오기
- given when then
- 테스트코드작성
- MySQL
- React+SpringBoot
- jsp
- 개발자취업
- 개발자취업후기
- jar빌드
- React.js
- JPAHibernate
- WebConfig
- SpringBoot JPA
- jstl
- 게시물상세
- 로컬이미지저장
- 비전공자개발자
Archives
- Today
- Total
인텔리가 '되고 싶은' 인텔리재이
[JSP + MyBatis] 8. 게시물 수정 (update), 삭제 (delete) 하기 본문
🕶 참고 포스팅
이번 포스팅에서는 게시판 상세페이지에 이어 게시물 수정, 삭제 기능을 구현해보겠습니다.🙂
게시물 수정은 상세페이지에서 버튼을 클릭하면 수정페이지로 이동하고,
게시물 삭제는 상세페이지에서 버튼을 클릭하면 바로 삭제되도록 구현할 예정입니다.🙄
화면 만들기
기존 화면이 있던 경로(src > main > webapp > WEB-INF > views > board 폴더) 에 update.jsp를 생성합니다.
detail.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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ include file="../include/style.jsp"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Detail Page</title>
</head>
<body>
<jsp:include page="../include/header.jsp"></jsp:include>
<h2 style="text-align: center">게시글 상세</h2>
<div class="container">
<form>
<div class="form-group">
<label>제목</label>
<p>${detail.subject}</p>
</div>
<div class="form-group">
<label>작성자</label>
<p>${detail.writer}</p>
</div>
<div class="form-group">
<label>작성날짜</label>
<p>
<fmt:formatDate var="resultRegDt" value="${detail.reg_date}"
pattern="yyyy-MM-dd" />
${resultRegDt}
</p>
</div>
<div class="form-group">
<label>내용</label>
<p>${detail.content}</p>
</div>
</form>
<button class="btn btn-outline-success"
onclick="location.href='/update/${detail.bno}'">수정</button>
<button class="btn btn-outline-danger"
onclick="location.href='/delete/${detail.bno}'">삭제</button>
<button class="btn btn-outline-secondary"
onclick="location.href='/list'">리스트</button>
</div>
<jsp:include page="../include/footer.jsp"></jsp:include>
</body>
</html>
- detail.jsp에서 수정 버튼을 클릭시 update.jsp 화면을 불러옵니다.
- detail.jsp에서 삭제 버튼을 클릭시 delete 기능을 실행합니다.
update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ include file="../include/style.jsp"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Update page</title>
</head>
<body>
<jsp:include page="../include/header.jsp"></jsp:include>
<h2 style="text-align: center">게시글 수정</h2>
<div class="container">
<form action="/updateProc" method="post">
<div class="form-group">
<label for="subject">제목</label> <input type="text"
class="form-control" id="subject" name="subject"
value="${detail.subject}">
</div>
<div class="form-group">
<label for="content">내용</label>
<textarea class="form-control" id="content" name="content" rows="3">
${detail.content}</textarea>
</div>
<input type="hidden" name="bno" value="${bno}" />
<button type="submit" class="btn btn-primary">수정완료</button>
</form>
</div>
<jsp:include page="../include/footer.jsp"></jsp:include>
</body>
</html>
- bootstrap을 통해 form과 버튼을 간편하게 만들었습니다.
- 제목과 내용만 수정이 가능하도록 하였습니다.
- 수정완료 클릭 시 form에 작성된 내용을 전송하며, controller의 updateProc 기능을 찾아 실행합니다.
- 수정완료 후 상세페이지로 이동되고, 변경사항을 확인할 수 있습니다.
기능 구현하기
DB에 저장된 데이터를 수정/삭제하기 위해, controller, domain, mapper, service에 코드를 추가하도록 하겠습니다.
src > main > java > com.example.demo 해당 경로에
controller, domain, mapper, service 패키지가 생성되어있는지 확인 후, 코드를 작성합니다.
1. controller > BoardController.java
- controller는 화면으로부터 데이터를 받아 VO에 담고, 이를 service로 값을 전달해주는 역할을 담당합니다.
- 이를 위해 service와의 의존성을 주입해주었습니다.
- 수정 버튼을 누르면, update.jsp 화면을 호출하고, update.jsp에서 수정완료 버튼을 누르면 updateProc가 실행됩니다.
- 삭제 버튼을 누르면 detail.jsp에서 넘겨준 bno parameter를 가지고 delete 기능을 실행합니다.
package com.example.demo.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.domain.BoardVO;
import com.example.demo.service.BoardService;
@Controller // 컨트롤러 빈으로 등록
public class BoardController {
@Resource(name = "com.example.demo.service.BoardService") // Service 의존성 주입
BoardService mBoardService;
@RequestMapping("/update/{bno}") // 게시글 수정폼 호출
private String boardUpdateForm(@PathVariable int bno, Model model) throws Exception {
model.addAttribute("detail", mBoardService.boardDetailService(bno));
return "board/update";
}
@RequestMapping("/updateProc")
private String boardUpdateProc(HttpServletRequest request) throws Exception {
BoardVO board = new BoardVO();
board.setSubject(request.getParameter("subject"));
board.setContent(request.getParameter("content"));
board.setBno(Integer.parseInt(request.getParameter("bno")));
mBoardService.boardUpdateService(board);
return "redirect:/detail/" + request.getParameter("bno");
}
@RequestMapping("/delete/{bno}")
private String boardDelete(@PathVariable int bno) throws Exception {
mBoardService.boardDeleteService(bno);
return "redirect:/list";
}
}
2. service > BoardService.java
- Service는 Controller로부터 데이터를 받고, 이를 Mapper로 전달해주는 역할을 담당합니다.
- 이를 위해 Mapper와의 의존성을 주입해주었습니다.
package com.example.demo.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.example.demo.domain.BoardVO;
import com.example.demo.mapper.BoardMapper;
@Service("com.example.demo.service.BoardService")
public class BoardService {
// Mapper 의존성 주입
@Resource(name = "com.example.demo.mapper.BoardMapper")
BoardMapper mBoardMapper;
// 게시물 수정
public int boardUpdateService(BoardVO board) throws Exception {
return mBoardMapper.boardUpdate(board);
}
// 게시물 삭제
public int boardDeleteService(int bno) throws Exception {
return mBoardMapper.boardDelete(bno);
}
}
3. mapper > BoardMapper.java
- Mapper 인터페이스는 Service로부터 데이터를 받고, 직접 DB에 접근하여 데이터를 처리합니다.
- Mapper.xml 에 작성된 SQL 쿼리문을 자바 인터페이스를 통해 호출하여 처리합니다.
package com.example.demo.mapper;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.example.demo.domain.BoardVO;
//DB에 접근하는 클래스
@Repository("com.example.demo.mapper.BoardMapper")
public interface BoardMapper {
// 게시글 수정
public int boardUpdate(BoardVO board) throws Exception;
// 게시글 삭제
public int boardDelete(int bno) throws Exception;
}
4. mapper > BoardMapper.xml
- 이곳에 작성된 SQL 쿼리문을 자바 인터페이스를 통해 호출하여 DB에 반영합니다.
- DB에서 파라미터로 넘어온 게시물 번호(bno)와 동일한 번호를 가진 게시물을 삭제합니다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.mapper.BoardMapper">
<update
id="boardUpdate"
parameterType="com.example.demo.domain.BoardVO"
>
UPDATE BOARD
SET
SUBJECT = #{subject}
,CONTENT = #{content}
WHERE BNO = #{bno}
</update>
<delete
id="boardDelete"
parameterType="int"
>
DELETE FROM BOARD WHERE BNO = #{bno}
</delete>
</mapper>
코드 작성 후, 기능이 잘 동작하는지 확인합니다!
이로써 (간단한) 게시물 조회, 작성, 수정, 삭제까지 CRUD 기능을 완성하였습니다😊
CRUD는 기본이지만 가장 중요한 기능인만큼 따라해보면서 익숙해진다면,
이를 바탕으로 한 추가적인 기능까지 구현할 수 있을 것입니다! 👍
'✨LEVEL UP🎇 > PROJECT' 카테고리의 다른 글
[JSP + MyBatis] 7. 게시물 상세페이지 조회하기 (0) | 2023.03.24 |
---|---|
[JSP + MyBatis] 6. 게시물 리스트 + JSTL (1) | 2023.03.06 |
[JSP + MyBatis] 5. 게시글 작성하기 (insert) (1) | 2023.02.07 |
[JSP + MyBatis] 4. 화면에 부트스트랩(Bootstrap) 적용하기 (0) | 2023.01.27 |
[JSP + MyBatis] 3. MySQL DB 연동하기 (0) | 2023.01.25 |
Comments