Spring Model(@ModelAttribute, @Requestparam)

고 연우·2022년 9월 19일
0

SpringBoot

목록 보기
2/8

Model

  • HashMap 형태 -> key, value 값 갖고 있음
  • 모델에 원하는 속성과 그것에 대한 값을 주어 전달할 뷰에 데이터 전달함
  • Spring에서 Controller의 메서드를 작성할 때 Model이라는 타입을 파라미터로 지정 가능.
  • Servelt의 request.setAttribute()와 유사한 역할.

<예시>

Controller 생성 -> 메소드 매개변수로 Model 타입의 model 변수 선언

import org.springframework.ui.Model;

@GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data", "hello!!");  //key, value 형식
        return "hello";
}
  • model.addAttribute("key";"value") 통해 view에 데이터 전달

@ModelAttribute

  • 사용자가 요청시 전달하는 값을 오브젝트 형태로 매핑해주는 어노테이션
  • 외부 데이터가 bean에 등록된 객체로 자동으로 변환되어 사용 가능
  • 스프링에서 Java Beans 규칙( Getter, Setter, 생성자 포함 )에 맞는 객체는 파라미터 전달이 자동으로 가능
    • 일반 변수의 경우, 자동 전달이 불가능하며 model 객체 통해서 전달 필요
  • 기본적으로 객체의 setter로 받아옴( Default 값 -> 권장됨 )

<예시>

	@Getter
	@Setter
	public class TestModel {
		private String name;
		private int age;
	}

	@RestController
	public class TestController {

		@GetMapping("/")
		public String getTestPage(@ModelAttribute TestModel testModel) {

			System.out.println(testModel.getname());
			System.out.pringln(testModel.getAge());
			return "test";
		}
	}
  • /?name=hyejeong&age=25 로 요청 -> name, age 값이 testModel 객체로 바인딩 됨( Setter 존재해야 함 )

@RequestParam

  • 사용자가 요청시 전달하는 값을 Controller 의 매개변수로 1:1 맵핑할 때 사용되는 어노테이션

<예시>

import org.springframework.web.bind.annotation.RequestParam;

@GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model) {

        model.addAttribute("name", name);
        return "hello-template";

    }

참고
https://nancording.tistory.com/90
https://galid1.tistory.com/769
https://iamdaeyun.tistory.com/entry/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%BB%A8%ED%8A%B8%EB%A1%A4%EB%9F%AC
https://velog.io/@sloools/Spring-Boot-%EC%BB%A8%ED%8A%B8%EB%A1%A4%EB%9F%AC-ModelAttribute-%EC%96%B4%EB%85%B8%ED%85%8C%EC%9D%B4%EC%85%98

0개의 댓글