728x90
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());
}


728x90
'BACKEND > SpringBoot' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| ์์ ์ผ์ ํ์ํ๊ธฐ( ์ง๋ฌธ, ๋ต๋ณ) (2) | 2023.11.13 |
|---|---|
| ๋ต๋ณ ์ญ์ (1) | 2023.11.13 |
| ์ง๋ฌธ ์ญ์ ์ฒ๋ฆฌ (0) | 2023.11.10 |
| ์ง๋ฌธ ์์ ์ฒ๋ฆฌ (0) | 2023.11.10 |
| ์ํฐํฐ ๋ณ๊ฒฝ ๊ธ์ด์ด ์ถ๊ฐ ๋ฐ ๊ธ ๋ชฉ๋ก,์์ธ๋ณด๊ธฐ,๋ต๋ณ์ ๋ฐ์ํ๊ธฐ (0) | 2023.11.10 |