@ModelAttribute

전승원·2021년 1월 8일
0

getHomePage 메소드를 보자. MessageForm 커맨드 객체를 넘겨줄 때, 나는 이 때까지 변수명인 newMessage 라는 이름으로 템플릿에 넘겨지는 줄 알았다.

하지만, 스프링은 @ModelAttribute("name") 설정이 되어 있지 않으면, 기본적으로 해당 POJO 클래스 이름의 앞글자만 소문자로 바꾸어서 템플릿에 넘겨준다.

따라서, 아래와 같이 ModelAttribute annotation 설정이 없는 경우 messageForm이라는 이름으로 템플릿에 넘겨진다.

만약, newMessage라는 이름으로 템플릿에 넘겨주고 싶을 경우에는 @ModelAttribute("newMessage") MessageForm newMessage 이렇게 넘겨 주면 될 것이다.


마찬가지로, PostMapping에서 커맨드 객체에 매핑된 데이터를 받아올 때도 동일하다. GetMapping에서 해당 커맨드 객체를 "newMessage"라는 이름으로 넘겨주었다면, PostMapping에서도 "newMessage"라는 이름으로 받아와야 하고,
"MessageForm"이라는 이름으로 넘겨주었다면, "MessageForm" 이라는 이름으로 받아와야 할 것이다.

사실, @ModelAttribute("name")을 모든 메소드에 동일하게 적용한다면 크게 문제될 것이 없는 부분이지만, @ModelAttribute를 사용하지 않고도 데이터를 넘길 수 있다는 것이 분명하기 때문에 이를 시도해보는 과정에서 조금 어려움을 겪었던 것 같다.

@Controller
public class HomeController {

    private MessageListService messageListService;

    public HomeController(MessageListService messageListService) {
        this.messageListService = messageListService;
    }

    @GetMapping("/home")
    public String getHomePage(MessageForm newMessage, Model model) {
        model.addAttribute("greetings", this.messageListService.getMessages());
        return "home";
    }

    @PostMapping("/home")
    public String addMessage(MessageForm newMessage, Model model) {
        messageListService.addMessage(messageForm.getText());
        model.addAttribute("greetings", messageListService.getMessages());
        messageForm.setText("");
        return "home";
    }

}
<!doctype html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Home</title>
</head>
<body>
<form action="#" th:object="${messageForm}" method="POST" th:action="@{'/home'}">
    <label for="newMessage">Submit a new message: </label>
    <input type="text" id="newMessage" name="messageForm" th:field="*{text}">
    <input type="submit">
</form>
<h1 th:each="msg : ${greetings}" th:text="${msg}" th:unless="${msg.contains('Goodbye')}">Hello, homepage!</h1>
</body>
</html>
profile
No pleasure, No gain

0개의 댓글

Powered by GraphCDN, the GraphQL CDN