티스토리 뷰

백기선 - 스프링 부트 개념과 활용

Spring HATEOAS

  • Hypermedia As The Engine Of Application State

  • ObjectMapper 제공(stater-web이 제공해서 우리는 stater-hateoas를 추가하지 않아도 사용가능하다.)

    • spring.jackson.*

    • Jackson2ObjectMapperBuilder

  • LinkDiscovers 제공

    • 클라이언트에서 링크 정보를 Rel 이름으로 찾을때 사용할 수 있는 XPath 확장 클래스

  • 컨트롤러에서 Resource 추가로 Http Response Body에 링크 추가하기, 테스트 코드로 추가된 링크 검증 예제

    package io.namjune.springbootconceptandutilization.controller;

    import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
    import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

    import io.namjune.springbootconceptandutilization.Hello;
    import org.springframework.hateoas.Resource;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    public class SampleController {

       @GetMapping("/hello")
       public Resource<Hello> hello() {
           Hello hello = new Hello();
           hello.setPrefix("Hey,");
           hello.setName("NJ");

           Resource<Hello> helloResource = new Resource<>(hello);
           helloResource.add(linkTo(methodOn(SampleController.class).hello()).withSelfRel());
           return helloResource;
      }
    }
    • ControllerTest

    package io.namjune.springbootconceptandutilization.controller;

    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(SampleController.class)
    public class SampleControllerTest {

       @Autowired
       MockMvc mockMvc;

       @Test
       public void hello() throws Exception {
           mockMvc.perform(get("/hello"))
              .andDo(print())
              .andExpect(status().isOk())
              .andExpect(jsonPath("$._links.self").exists());
      }
    }
    • 결과

    MockHttpServletResponse:
              Status = 200
      Error message = null
            Headers = {Content-Type=[application/hal+json;charset=UTF-8]}
        Content type = application/hal+json;charset=UTF-8
                Body = {"prefix":"Hey,","name":"NJ","_links":{"self":{"href":"http://localhost/hello"}}}
      Forwarded URL = null
      Redirected URL = null
            Cookies = []







댓글
댓글쓰기 폼