[Sprng] 요청파라미터 > @ModelAttribute

| 목표: @ModelAttribute의 사용 방법

  • URL의 파라미터로 username, age 값 요청이 왔을 경우.
    @ResponseBody
    @RequestMapping("/model-attribute-v1")
    public String modelAttributeV1(@RequestParam String username, @RequestParam int age) {
        HelloData helloData = new HelloData();
        helloData.setUsername(username);
        helloData.setAge(age);
        log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
        log.info("helloData={}", helloData);
        return "ok";
    }​

위의 소스를 @ModelAttribute 사용하여 간단하게 바꿀수 있다.

    @ResponseBody
    @RequestMapping("/model-attribute-v1")
    public String modelAttributeV1(@ModelAttribute HelloData helloData) {
        log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
        log.info("helloData={}", helloData);
        return "ok";
    }

참고로 경우에 따라 @ModelAttribute 생략 가능하다.

댓글

Designed by JB FACTORY