Jun's note

[Spring MVC] @ModelAttribute 본문

Programming/Spring

[Spring MVC] @ModelAttribute

junning 2022. 11. 3. 22:22
728x90

@ModelAttribute는 Spring MVC에서 사용된다. (주로 jsp와 같은 뷰템플릿과 함께 사용한다.)

 

- 동작방식

예시코드 참고해서 정리해본다.

@Controller
public class UserController {

    @Autowired
    private UserService service;
 
    @GetMapping("/user-info")
    public String getUserInfo(@ModelAttribute("user") UserInfo userInfo, Model model) {
        
        model.addAttribute("result", service.getUserInfo(userInfo));   //userInfoVO 반환  //Model
       
        return "user-info";			//View
    }
}
public class UserInfo{
	private String userName;
    	private int userAge;
    	private String userNickname;
        
        //getter 구현 되어있다 가정
}

http://localhost:8080/user-info?userName=junny&userAge=23&userNickname=jun

  1. @ModelAttribute 어노테이션이 붙은 객체(userInfo)를 자동으로 생성한다.   (이때 UserInfo는 빈(beans)클래스다)
  2. 위 url을 통해, HTTP로 넘어 온 값들을 자동으로 바인딩한다.
  3. @ModelAttribute 어노테이션이 붙은 객체(userInfo)가 자동으로 Model 객체에 추가되고, 따라서 userInfo가 .jsp 뷰단까지 전달이 된다.

 

 

- Model의 역할

  • Model 객체는 Controller 에서 생성된 데이터를 담아 View 로 전달할 때 사용하는 객체이다.
  • Servlet의 request.setAttribute() 와 비슷한 역할
  • addAttribute("key", "value") 메서드를 이용

+

@ModelAttribute : SpringMVC에서 사용

@RequestParam, @RequestBody, @RequestPart: SpringBoot에서 사용

SpringMVC와 SpringBoot이 서로 비슷하다고 생각했는데 알면 알수록 다른점들이 있어 Spring 프레임워크에 대해 더 알아봐야겠다.

Comments