20250731 - 학습일지

창훈·2025년 7월 31일

static에 등록한 css 파일연결

  • staict 폴더에 등록한 경우
 <link rel="stylesheet" type="text/css" th:href="@{/style.css}">
  • 외부 링크를 이용한 경우
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-LN+7fdVzj6u52u30Kp6M/trliBMCMKTyK833zpbD+pXdCLuTusPj697FH4R/5mcr" crossorigin="anonymous">

Answer 등록

  • AnswerController 클래스에서 POST Request를 수신하기 위해 RequestMapping, RequiredArgsConstructor, Controller annotation이 선언됨
  • 자료 수신과 저장을 위한 questionService, answerService 객체 선언
@RequestMapping("/answer")
@RequiredArgsConstructor
@Controller
public class AnswerController {
    private final QuestionService questionService;
    private final AnswerService answerService;

    @PostMapping("/create/{id}")
    // @ResponseBody
    public String createAnswer(Model model, @PathVariable("id") Integer id, @RequestParam(value="content") String content) {
        Question question = this.questionService.getQuestion(id);
        this.answerService.create(question, content);
        return String.format("redirect:/question/detail/%s", id);

    }
}
  • form action="/answer/create/3" method="post" 형식으로 정의된 client 로 부터 submit이 실행되면 createAnswer 메소드가 실행되면서 Model model 매개변수를 통해 컨트롤러에서 view 또는 service 전달할 데이터들을 객체화 함(스프링 MVC)

  • @PathVariable("id") Integer id 는 URL PATH로 정의 된 값(위 예시에 따르면 3)에 대한 정의

  • @RequestParam(value="content") String content 는 FORM DOM에서 선언된 POST.REQUEST에 포함된 객체 content를 처리하기 위해 매개변수를 정의 함. (textarea name="content")

  • Question question = this.questionService.getQuestion(id); QuestionService 크래스에 선언된 public Question getQuestion(Integer id) 함수를 호출하여 question 인스턴스에 관련 값들을 db에서 가져옴

  • this.answerService.create(question, content); AnswerService 클래스 내에 선언된 create 메소드를 호출하여 그 결과를 db에 저장함 answerRepository.save(answer);

  • ToDolist.. should be continued...

@RequiredArgsConstructor
@Service
public class AnswerService {
    private final AnswerRepository answerRepository;

    public void create(Question question, String content) {
        Answer answer = new Answer();
        answer.setContent(content);
        answer.setCreateDate(LocalDateTime.now());
        answer.setQuestion(question);
        this.answerRepository.save(answer);
    }
}

FORM : POST

<form th:action="@{|/answer/create/${question.id}|}" method="post">
    <textarea name="content" id="content" rows="15"></textarea>
    <input type="submit" value="답변등록">
</form>
  • th:action은 Thymeleaf에서 form의 action 속성을 설정할 때 사용하는 속성.
  • 일반적인 HTML에서는 action="/answer/create"처럼 경로를 지정하지만 Thymeleaf에서는 동적으로 값을 넣어야 할 때 ${...} 문법을 사용.
  • @{...}는 URL을 생성하는 Thymeleaf 문법

URL Perfix

import org.springframework.web.bind.annotation.RequestMapping; // url prefix

@RequestMapping("/question") // url prefix
... 중량 ----
    //@GetMapping("/question/list")
    @GetMapping("/list")    // url perfix
    public String list(Model model) {
        List<Question> questionList = this.questionService.getList();
        model.addAttribute("questionList", questionList);
        return "question_list";
    }
    
    //@GetMapping("/question/list")
    @GetMapping("/list")    // url perfix
    public String list(Model model) {
        List<Question> questionList = this.questionService.getList();
        model.addAttribute("questionList", questionList);
        return "question_list";
    }    

QuestionService

HTTP 응답 코드

200 : 요청이 정상적으로 처리(SUCCESS)
300 : 요청이 REDIRECT 됨
400 : 클라이언트 요청에 문제가 있을 때
500 : 서버 사이트 문제 시
1xx (Informational):
Indicates that the server has received the request and is continuing the process. Examples include 100 Continue and 101 Switching Protocols.
2xx (Successful):
Indicates that the request was successfully received, understood, and accepted. Examples include 200 OK, 201 Created, and 204 No Content.
3xx (Redirection):
Indicates that further action needs to be taken by the client to complete the request, usually involving a redirection to a different URL. Examples include 301 Moved Permanently and 302 Found.
4xx (Client Error):
Indicates that the client's request contains an error and cannot be fulfilled by the server. Examples include 400 Bad Request, 401 Unauthorized, 403 Forbidden, and 404 Not Found.
5xx (Server Error):
Indicates that the server failed to fulfill a valid request due to an issue on the server's side. Examples include 500 Internal Server Error, 502 Bad Gateway, and 503 Service Unavailable.

profile
한줄소개불가

0개의 댓글