BACKEND/SpringBoot

답변 수정

죠으닝 2023. 11. 13. 09:48

 

 

 

question_detail.html

          <div class="my-3">
            <a
              th:href="@{|/answer/modify/${answer.id}|}"
              class="btn btn-sm btn-outline-secondary"
              sec:authorize="isAuthenticated()"
              th:if="${answer.author != null and #authentication.getPrincipal().getUsername() == answer.author.username}"
              th:text="수정"
            ></a>
          </div>

 

 

답변에 수정하기 버튼 추가함

 

 

 

AnswerService

	//답변 조회하기
	public Answer getAnswer(int id) {
		Optional<Answer> answer = aRepo.findById(id);
		if(answer.isPresent()) {
			return answer.get();
		}
		else {
			throw new DataNotFoundException("answer not found");
		}
	}
	
	//답변 수정하기 
	public void modify(Answer answer,String content) {
		answer.setContent(content);
		answer.setModifyDate(LocalDateTime.now());
		aRepo.save(answer);
	}

 

 

AnswerController-get

	//답변 수정 전 답변 내용 출력
	@PreAuthorize("isAuthenticated()")
	@GetMapping("/modify/{id}")
	public String answerModify(AnswerForm answerForm,@PathVariable("id") int id,Principal principal) {
		Answer answer = aService.getAnswer(id);//답변조회하기
		if(!answer.getAuthor().getUsername().equals(principal.getName())) {
			throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"수정 권한이 없습니다.");
		}
		answerForm.setContent(answer.getContent());
		return "answer_form";
	}

 

 

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head th:replace="layout::head"></head>
  <body>
    <nav th:replace="layout::nav"></nav>
    <div class="container my-3">
      <h5 class="my-3 border-bottom pb-2">답변 수정</h5>
      <form th:object="${answerForm}" method="post">
        <input
          type="hidden"
          th:name="${_csrf.parameterName}"
          th:value="${_csrf.token}"
        />
        <div th:replace="layout::formErrors"></div>
        <div class="mb-3">
          <label for="content" class="form-label">내용</label>
          <textarea
            th:field="*{content}"
            class="form-control"
            rows="10"
          ></textarea>
        </div>
        <input type="submit" value="저장하기" class="btn btn-primary my-2" />
      </form>
    </div>
  </body>
</html>

 

 

 

화면 출력 테스트하기 

 

 

 

AnswerController-post

저장하기 버튼 누르면 실제로 수정 처리 하는 코드 

	//답변 수정 처리
	@PreAuthorize("isAuthenticated()")
	@PostMapping("/modify/{id}")
	public String answerModify(@Valid AnswerForm answerForm, BindingResult result,
								@PathVariable("id") int id, Principal principal) {
		if(result.hasErrors()) {
			return"answer_form";
		}
		Answer answer = aService.getAnswer(id);//답변 조회 
		if(!answer.getAuthor().getUsername().equals(principal.getName())) {
			//만약 답변 작성자의 id와 현재 로그인 중인 유저의 id와 일치하지 않으면
			throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"수정권한이 없습니다.");
		}
		aService.modify(answer, answerForm.getContent());//답변 id와 , 수정 된 답변 내용 저장
		return String.format("redirect:/question/detail/%s", answer.getQuestion().getId());
	}