개발놀이터

스프링 요청파라미터 본문

Spring/Spring

스프링 요청파라미터

마늘냄새폴폴 2021. 8. 19. 09:38

*HTTP 요청 파라미터 - @RequestParam

스프링이 제공하는 @RequestParam을 사용하면 요청 파라미터를 매우 편리하게 사용할 수 있다.

@RequestMapping("/request-param-v2")
public String requestParamV2 (@RequestParam("username") String memberName, @RequestParam("age") int memberAge) {
...
}
이런식으로 RequestParam을 이용하면 request.getParameter("username")과 같은 효과를 볼 수 있다.


@RequestMapping("/request-param-v3)
public String requestParamV3 (@RequestParam String username, @RequestParam int age) 파라미터 이름과 변수 이름이 같다면 이런식으로 간략하게 표현 할 수 있다.


*HTTP 요청 파라미터 - @ModelAttribute
@ResponseBody
    @RequestMapping("/model-attribute-v1")
    public String modelAttributeV1(@RequestParam String username, @RequestParam int age) {
        HelloData helloData = new HelloData();
        helloData.setAge(age);
        helloData.setUsername(username);

        log.info("username={}", helloData.getUsername());
        log.info("age={}", helloData.getAge());

        return "ok";
    }
이렇게 귀찮게 길게 써야했던 코드들이
@ResponseBody
    @RequestMapping("/model-attribute-v2")
    public String modelAttributeV2(@ModelAttribute HelloData helloData) {
        log.info("username={}", helloData.getUsername());
        log.info("age={}", helloData.getAge());

        return "ok";
    }
이렇게 간결하게 줄어든다

스프링 MVC는 @ModelAttribute 가 있으면 다음을 실행한다
1. HelloData 객체를 생성한다.
2. 요청 파라미터의 이름으로 HelloData객체의 프로퍼티를 찾는다. 그리고 해당 프로퍼티의 setter를 호출해서 파라미터의 값을 입력한다.
3. 예) 파라미터 이름이 username이면 setUsername() 메서드를 찾아서 호출하면서 값을 입력한다.

프로퍼티란?
객체에 getUsername(), setUsername() 메서드가 있으면, 이 객체는 username이라는 프로퍼티를 가지고 있다. username프로퍼티의 값을 변경하면 setUsername()이 호출되고 조회하면 getUsername()이 호출된다.

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

스프링 HTTP요청 메시지 - JSON  (0) 2021.08.19
스프링 HTTP 요청 메시지 - 단순 텍스트  (0) 2021.08.19
스프링 요청매핑  (0) 2021.08.19
스프링 로깅  (0) 2021.08.19
스프링 MVC 구조  (0) 2021.08.19