Java/Spring

[Spring]Model 객체와 @ModelAttribute

뉴벡엔드 2024. 4. 2. 12:52

Spring Model 객체

Spring MVC(Model-View-Controller) 아키텍처의 일부로, Controller에서 View로 데이터를 전달하는 데 사용됩니다. Controller에서 처리한 데이터나 비즈니스 로직의 결과를 Model 객체에 추가하면, Spring MVC는 이 Model 객체를 사용하여 View를 렌더링할 때 필요한 데이터를 제공합니다.

 

 

예시)

 

html

    <form action="/board/write" method="post">
        <input type="text" name="title">
        <textarea name="content"></textarea>
        <button type="submit">작성</button>
    </form>

 

controller

    @PostMapping("/board/write")
    public String boardWrite(String title, String content, Model model) {
        
        model.addAttribute("title", title);
        model.addAttribute("content", content);

        return "boardWriteEnd";
    }

 

 


 

@ModelAttribute

Spring MVC에서 모델 데이터를 컨트롤러의 메소드 파라미터나 메소드 자체에 바인딩하는 데 사용되는 어노테이션입니다. 이 어노테이션을 사용하면 HTTP 요청 파라미터를 객체에 바인딩하거나, 모델에 데이터를 추가하여 뷰에 전달할 수 있습니다.

 

 

 

1. 메소드 파라미터에 사용

메소드 파라미터에 사용할 때, 스프링은 HTTP 요청 파라미터를 해당 파라미터 타입의 객체로 바인딩합니다. 이는 폼 데이터나 쿼리 파라미터를 도메인 객체에 자동으로 바인딩하고자 할 때 유용합니다.

 

예시)

 

BoardForm class는 String title, String content를 가짐

    @PostMapping("/board/write")
    public String boardWrite(@ModelAttribute("board") BoardForm form) {

        System.out.println("title = " + form.getTitle() + ", content = " + form.getContent());

        return "boardWriteEnd";
    }

 

    <p th:text="${board.title}"></p>
    <p th:text="${board.content}"></p>

 

 

2. 메소드 레벨에 사용

컨트롤러 클래스 내의 메소드에 적용하면, 해당 컨트롤러의 모든 뷰에 공통으로 사용될 모델 속성을 정의할 수 있습니다. 이 메소드는 컨트롤러 내의 다른 @RequestMapping 메소드가 호출되기 전에 실행되며, 메소드에서 반환된 객체는 모델에 자동으로 추가됩니다. 이 방법은 여러 뷰에서 공통적으로 사용되는 모델 속성을 설정할 때 유용합니다.

 

 

예시)

모든 뷰에서 사용자 세션 정보를 필요로 한다면, 다음과 같이 작성할 수 있습니다:

 

@ModelAttribute
public void addUserToModel(Model model) {
    User user = userService.getCurrentUser(); // 현재 사용자 정보를 조회
    model.addAttribute("currentUser", user);
}

 

] 이 메소드는 모델에 "currentUser"라는 이름으로 사용자 객체를 추가하며, 이는 모든 뷰에서 사용할 수 있게 됩니다.

반응형

'Java > Spring' 카테고리의 다른 글

[Spring]@PageableDefault (페이징 처리)  (0) 2024.04.08
[Spring] @DeleteMapping 사용방법  (0) 2024.04.02
[Spring]MariaDB 연동  (0) 2024.03.28
[Spring]AOP  (0) 2024.03.28
[Spring]JdbcTemplate  (0) 2024.03.28