[6] 작성한 게시글 수정하기 구현
들어가며
이전 포스팅에서는 조회수를 구현해봤다. 이번에는 작성한 게시글을 수정을 구현해볼 것입니다.
사전 준비
게시글 수정하기 구현
Entity
Board.class
public void update(String title, String content){
this.title=title;
this.content = content;
}
board 엔티티에다가 update()메소드를 추가한다.
( 변경 작업을 수행할 때, 엔티티에서 값을 가져와서 업데이트하는 방식을 고려하여 해당 엔티티 클래스에 업데이트 메서드를 작성했습니다.)
Service
BoardServiceImpl
@Override
public Board updateBoard(BoardDto boardDto) {
Board byBoardId = findByBoardId(boardDto.getId());
byBoardId.update(boardDto.getTitle(), boardDto.getContent());
return boardRepository.save(byBoardId);
}
updateBoard() : dto로 넘어온 id를 가져와 실제 객체를 가져와 update()실행후 저장
Controller
BoardController
@GetMapping("/board/update/{id}")
public String updateGetBoard(@PathVariable(name = "id") Long id,Model model){
Board byBoardId = boardService.findByBoardId(id);
model.addAttribute("board",byBoardId);
return "board/updateBoard";
}
@PutMapping("/board/update")
@ResponseBody
public ResponseEntity<?> updateBoardAfter(@RequestBody BoardDto boardDto){
try{
Board board = boardService.updateBoard(boardDto);
return ResponseEntity.ok(board);
}catch (Exception e){
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("오류 발생");
}
}
GetMapping으로 게시글을 수정할수 있게 매핑해준다
resful api 형태로 업데이트코드 작성
update 동작확인
postman으로 확인해보면 정상적으로 값을 수정하는것을 볼수있다.
HTML
updateBoard.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments/header :: header"></head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script th:inline="javascript">
function updateBoard(){
const title = document.getElementById('title_input').value;
const content = document.getElementById('content_input').value;
const id = document.getElementById('input_id').value;
var boardDto = {
"id" : id,
"title" : title,
"content" : content
}
$.ajax({
url : "/board/update",
method : "put",
contentType :"application/json",
data : JSON.stringify(boardDto),
success : function (response){
alert("변경성공");
window.location.href="/board";
},error : function (xhr){
if(xhr.status === 500){
alert("변경중 오류 발생");
}
}
});
}
</script>
<body>
<div class="container mt-5" th:object="${board}">
<input type="hidden" id="input_id" th:value="*{id}"/>
<div class="block table-responsive grid-view">
<table class="table table-bordered">
<caption class="hidden">만든이 : 코드폭탄</caption>
<tbody>
<tr>
<th><label th:for="writer">작성자</label></th>
<td>
<input class="form-control" id="writer_input" type="text" th:value="*{writer}" readonly ></td>
</tr>
<tr>
<th><label th:for="title">제목</label></th>
<td colspan="3"><input class="form-control" id="title_input" type="text" th:value="*{title}"></td>
</tr>
<tr>
<th><label th:for="password">비밀번호</label></th>
<td colspan="3"><input class="form-control" th:value="*{password}" readonly type="password" ></td>
</tr>
<tr>
<th><label th:for="content">내용</label></th>
<td colspan="3">
<textarea class="form-control" id="content_input" rows="5" cols="80" style="height: 235px; width: 614px;" th:text="*{content}"></textarea>
</td>
</tr>
</tbody>
</table>
<button type="button" onclick="updateBoard()">수정하기</button>
</div>
</div>
</body>
</html>
수정하기 버튼 클릭시 ajax 통신으로 우리가 만들었던 "/board/update"를 실행해준다.
변경전
수정하기
변경후
올바르게 게시글이 수정되는것을 볼수 있다.
게시물 수정 검증
하지만 지금 상태로 보내는것은 모든 사용자가 게시글을 수정할수있다. 이제 검증을 통해서 작성한 사용자와 게시글의 비밀번호가 일치할때만 수정할수있도록 구현해보자
MemberServiceImpl
public Integer passwordVerify(Long boardId, String password,String username){
Board byBoardId = findByBoardId(boardId);
String boardPassword = byBoardId.getPassword();
Member memberUsername = memberService.findByUsername(username);
if (boardPassword.equals(password)) {
if (memberUsername == null||!(byBoardId.getWriter().equals(username))) {
return 2; // 비밀번호는 o ,사용자 인증은 x
}
return 1; //성공시 1로반환
}
return 0;
}
넘어온 파라미터 값으로 검증을하고 모두 일치할시에는 1로 반환 비밀번호는 일치하나 사용자가 일치하지않을경우는 2 모두 일치하지 않으면 0을 반환한다.
BoardController
@PostMapping("/password/verify")
@ResponseBody
public ResponseEntity<?> verifyPassword(@RequestBody BoardDto boardDto){
try {
String password = boardDto.getPassword(); //입력한 비밀번호
String dtoUsername = boardDto.getMemberDto().getUsername(); //사용자 정보
Long boardId = boardDto.getId(); //게시글 번호
Integer integer = boardService.passwordVerify(boardId, password, dtoUsername);;
if (integer==2){
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("등록한 사용자만 수정할수 있습니다.");
} else if (integer==1){
return ResponseEntity.ok(integer);
}
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("비밀번호가 일치하지 않습니다.");
}catch (Exception e){
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("오류발생");
}
}
Json 형태로 값을 넘겨주고 passwordVerify에서 2로 반환시에는 401(UNAUTHORIZED)를 반환하고, 1일때는 400(BAD_REQUEST),1일때는 "1"을반환한다.
사용자 검증 성공시
상태코드 200일 날리며 body에 1이 넘어온다.
사용자 검증 실패시(비밀번호)
상태코드 400을 날리며 Body에는 "비밀번호가 일치하지 않습니다"가 넘어온다
사용자 검증 실패시(로그인한 사용자)
상태코드 401을 날리며 Body에는 "등록한 사용자만 수정할수 있습니다"가 넘어온다.
이로써 서버에서 사용자 검증을 구현해봤다
이제 뷰에서 수정 버튼을 클릭시에 모달창을 띄어 비밀번호를 입력하고 이동수정 폼으로 넘어가는 코드를 작성해보자.
boardInfo.html
function verifyPassword() {
var passwordInput = document.getElementById('password').value;
var id = document.getElementById('input_id').value;
const loginMember= document.getElementById('loginMember_username').value;
var dto ={
"id" : id,
"password" : passwordInput,
"memberDto" :{
"username" : loginMember
}
}
$.ajax({
url : "/password/verify",
method : "post",
contentType : "application/json",
data : JSON.stringify(dto),
success : function (response){
if (response === 1){
alert("비밀번호 검증 성공");
window.location.href = "/board/update/" + id;
}
},
error : function (xhr){
if (xhr.status===500){
alert("오류 발생");
}
if (xhr.status===400){
alert("비밀번호가 일치하지 않습니다.");
}
if (xhr.status===401){
alert("등록한 사용자만 수정할수 있습니다.");
}
}
});
}
사용자 검증 기능을 <script> 안에 추가해준다.
<div id="passwordModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal()">×</span>
<label for="password">비밀번호를 입력하세요:</label>
<input type="password" id="password">
<button onclick="verifyPassword()">확인</button>
</div>
</div>
모달창을 사용해 사용자 검증을 할예정이여서 <body> 내부에 모달창 코드를 추가해준다.
function updateBoardPage(){
if(loginverfiy===true) {
openModal();
}if(loginverfiy===false) {
alert("권한이 없습니다.");
}
}
function openModal() {
document.getElementById('passwordModal').style.display = 'block';
}
function closeModal() {
document.getElementById('passwordModal').style.display = 'none';
}
클라이언트에서도 간단하게 검증할수 있도록 function updateBoardPage() 변경해준다.
구현 테스트
영상에서 보이는것처럼 검증을 구현해봤다 만약 다른 아이디로 수정을 진행하면 작성한 사용자만 수정할수있다고 메시지가 나올것이다.
다음으로
이번포스팅에서는 게시글 수정 기능을 구현해봤다. 다음 포스팅에서는 똑같은 방법으로 삭제 기능도 구현해볼 예정입니다. 감사합니다!!