Archive/Spring Web MVC

3.3 핸들러 메소드 (execute & using handler method) (작성중)

nimkoes 2021. 7. 15. 00:02
728x90

 

 

이번에는 handler method 에서 사용할 수 있는 다양한 argument 에 대해 정리한다.

여러 포스트로 나누어 정리하지 않고 이번에 자주 사용하는 방법 위주로 이곳에 정리할 예정이다.

 

spring framework document 의 Method Arguments 와 강의 내용을 참고하여 정리했다.

 

 


정리 내용

- @PathVariable 과 @MatrixVariable

 

 


 

@PathVariable 과 @MatrixVariable

 

PathVariable api 문서를 보면 @RequestMapping annotation 이 붙은 handler method 에서 사용할 수 있는 URI template 변수에 바인딩 되는 parameter 에 사용할 수 있다고 되어 있다.

 

@PathVariable 을 테스트 해보기 위해 다음과 같이 코드를 수정 하였다.

 

 

반환 값으로 사용 할 UserInfo 클래스를 만들었다.

 

package me.nimkoes;

import lombok.Getter;
import lombok.Setter;

@Getter @Setter
public class UserInfo {
    private int id;
    private String name;
}

 

그리고 MyHelloController 클래스의 handler mehtod 를 다음과 같이 @PathVariable 을 사용하도록 수정했다.

 

package me.nimkoes;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyHelloController {

    @GetMapping("/hello/{id}")
    @ResponseBody
    public UserInfo hello(@PathVariable int id) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);

        return userInfo;
    }

}

 

@GetMapping annotation 의 meta annotation 으로 @RequestMapping annotation 을 사용하기 때문에 @PathVariable 을 사용할 수 있다.

@PathVariable 관련된 문서를 봤다면 알겠지만 바인딩 할 URI template 의 값을 알고 있다면 다음과 같이 메소드 내에서 다른 변수로 사용할 수 있다.

 

package me.nimkoes;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyHelloController {

    @GetMapping("/hello/{id}")
    @ResponseBody
    public UserInfo hello(@PathVariable(value = "id") int paramId) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(paramId);

        return userInfo;
    }

}

 

하지만 특별한 경우가 아니라면 굳이 이렇게 사용 할 필요는 없다.

이 hander method 가 정상 동작 하는지 확인해보기 위한 테스트 코드를 작성 했다.

 

package me.nimkoes;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

@RunWith(SpringRunner.class)
@WebMvcTest
public class MyHelloControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void helloTest() throws Exception {

        mockMvc.perform(get("/hello/1234"))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(jsonPath("id").value(1234))
        ;

    }
}

 

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /hello/1234
       Parameters = {}
          Headers = {}
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = me.nimkoes.MyHelloController
           Method = public me.nimkoes.UserInfo me.nimkoes.MyHelloController.hello(int)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = {"id":1234,"name":null}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

 

URI 정보에서 argument 를 추출해내는 것과 관련해서 @PathVariable 이외에 @MatrixVariable 이 있다.

MatrixVariable api 문서를 보면 이것 역시 @RequestMapping annotation 이 붙은 handler method 에 사용할 수 있고, URI path 상에 name-value 쌍으로 이루어진 내용을 참고해서 argument 로 사용할 수 있다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90