티스토리 뷰

study/springboot

008. Controller request mapping

까오기 2022. 5. 11. 18:49

요청 시 컨트롤러의 메소드에 어떻게 매핑되는지 기본적인 annotation에 대해 이해한다.  

 

Request Mapping Annotation 종류 

Annotation Target Method Remark
@RequestMapping @Target({ElementType.TYPE,
  ElementType.METHOD})
All 전체 
@GetMapping @Target(ElementType.METHOD) RequestMethod.GET 조회
@PostMapping @Target(ElementType.METHOD) RequestMethod.POST 등록, 생성, 저장
@PutMapping @Target(ElementType.METHOD) RequestMethod.PUT 수정
@DeleteMapping @Target(ElementType.METHOD) RequestMethod.DELETE 삭제, 제거

예제 

@RestController
@RequestMapping("/controller/mapping")
public class RequestMappingAPIController {

    /**
     * 모든 메소드 가능
     * @return
     */
    @RequestMapping("/requestMapping")
    public ResponseEntity<String> requestMapping() {
        return ResponseEntity.ok("requestMapping");
    }
    
    /**
     * @RequestMapping(method = RequestMethod.GET)와 동일  
     * @return
     */
    @GetMapping
    public ResponseEntity<String> getMapping() {
        return ResponseEntity.ok("getMapping");
    }
    
    /**
     * @RequestMapping(method = RequestMethod.POST)와 동일  
     * @return
     */
    @PostMapping
    public ResponseEntity<String> postMapping() {
        return ResponseEntity.ok("postMapping");
    }

    /**
     * @RequestMapping(method = RequestMethod.PUT)와 동일  
     * @return
     */
    @PutMapping
    public ResponseEntity<String> putMapping() {
        return ResponseEntity.ok("putMapping");
    }

    /**
     * @RequestMapping(method = RequestMethod.DELETE)와 동일  
     * @return
     */
    @DeleteMapping
    public ResponseEntity<String> deleteMapping() {
        return ResponseEntity.ok("deleteMapping");
    }

    /**
     * @RequestMapping(method = RequestMethod.GET, path="/test1")와 동일  
     * @return
     */
    @GetMapping("/test1")
    public ResponseEntity<String> getMappingTest() {
        return ResponseEntity.ok("getMapping-test1");
    }
    
    /**
     * 복수개의 주소에 대한 예제  
     * @return
     */
    @GetMapping({"/test2","/test-mapping"})
    public ResponseEntity<String> getMappingTest2() {
        return ResponseEntity.ok("getMapping-test2");
    }

}

테스트 

@WebMvcTest(RequestMappingAPIController.class)
class RequestMappingAPIControllerTest {

    @Autowired 
    private MockMvc mockMvc;
    
    private static final String ROOT_URI = "/controller/mapping";
    
    /**
     * @RequestMapping 테스트, get/post/put/delete로 요청을 해본다. 
     * @throws Exception
     */
    @ParameterizedTest
    @CsvSource({
        ROOT_URI+"/requestMapping,requestMapping"
        , ROOT_URI+",getMapping"
        , ROOT_URI+"/test1,getMapping-test1"
        , ROOT_URI+"/test2,getMapping-test2"
        , ROOT_URI+"/test-mapping,getMapping-test2"
        })
    void requestMapping(String uri, String expected) throws Exception {
        MockHttpServletRequestBuilder mrbuilder = MockMvcRequestBuilders.get(uri).contentType(MediaType.APPLICATION_JSON);
        execute(mrbuilder, expected);
    }

    private void execute(MockHttpServletRequestBuilder mrbuilder, String expected) throws Exception {
        MvcResult result = mockMvc.perform(mrbuilder)
                .andDo(print())
                .andExpect(status().isOk())
                .andReturn();
        String content = result.getResponse().getContentAsString();
        assertThat(content).isEqualTo(expected);
    }
    
    
    /**
     * @PostMapping 테스트 
     * @throws Exception
     */
    @Test
    void postMapping() throws Exception {
        MockHttpServletRequestBuilder mrbuilder = MockMvcRequestBuilders.post(ROOT_URI).contentType(MediaType.APPLICATION_JSON);
        execute(mrbuilder, "postMapping");
    }
    
    /**
     * @PutMapping 테스트 
     * @throws Exception
     */
    @Test
    void putMapping() throws Exception {
        MockHttpServletRequestBuilder mrbuilder = MockMvcRequestBuilders.put(ROOT_URI).contentType(MediaType.APPLICATION_JSON);
        execute(mrbuilder, "putMapping");
    }
    
    /**
     * @DeleteMapping test
     * @throws Exception
     */
    @Test
    void deleteMapping() throws Exception {
        MockHttpServletRequestBuilder mrbuilder = MockMvcRequestBuilders.delete(ROOT_URI).contentType(MediaType.APPLICATION_JSON);
        execute(mrbuilder, "deleteMapping");
    }

}

소스 : https://github.com/kkaok/study-springboot/blob/main/src/main/java/eblo/study/springboot/controller/RequestMappingAPIController.java

'study > springboot' 카테고리의 다른 글

010. Request parameter 처리  (0) 2022.05.14
009. controller pathvariable 처리  (0) 2022.05.12
007. 기본 설정 추가 및 실행  (0) 2022.05.11
006. 사용자 배너 추가  (0) 2022.05.11
005. Spring annotaion  (0) 2022.05.11
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함