Spring MVC - Using RequestEntity and ResponseEntity

[Updated: Mar 9, 2016, Created: Mar 9, 2016]

org.springframework.http.RequestEntity<T> extends HttpEntity and adds additional information of HTTP method and uri to the request.

org.springframework.http.ResponseEntity<T> also extends HttpEntity, where we can add additional HttpStatus (see also @ResponseStatus) to the response.


In this example we are going to show the use of RequestEntity and RequestResponse with JUnit tests.



Handling request having String body

@Controller
@RequestMapping
public class MyController {

    @RequestMapping("test")
    public ResponseEntity<String> handleRequest (RequestEntity<String> requestEntity) {
        System.out.println("request body : " + requestEntity.getBody());
        HttpHeaders headers = requestEntity.getHeaders();
        System.out.println("request headers : " + headers);
        HttpMethod method = requestEntity.getMethod();
        System.out.println("request method : " + method);
        System.out.println("request url: " + requestEntity.getUrl());

        ResponseEntity<String> responseEntity = new ResponseEntity<>("my response body",
                                                                     HttpStatus.OK);
        return responseEntity;
    }
}


The unit test

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class ControllerTest {

    @Autowired
    private WebApplicationContext wac;
    private MockMvc mockMvc;

    @Before
    public void setup () {
        DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
        this.mockMvc = builder.build();
    }

    @Test
    public void testUserController () throws Exception {
        MockHttpServletRequestBuilder builder =
                                      MockMvcRequestBuilders.post("/test")
                                        .header("testHeader",
                                                "headerValue")
                                        .content("test body");
        this.mockMvc.perform(builder)
                    .andExpect(MockMvcResultMatchers.status()
                                                    .isOk())
                    .andDo(MockMvcResultHandlers.print());



Output:

request body : test body
request headers : {testHeader=[headerValue], Content-Length=[9]}
request method : POST
request url: http://localhost:80/test

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /test
       Parameters = {}
          Headers = {testHeader=[headerValue]}

Handler:
             Type = com.logicbig.example.MyController
           Method = public org.springframework.http.HttpEntity<java.lang.String> com.logicbig.example.MyController.handleRequest(org.springframework.http.RequestEntity<java.lang.String>)

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=[text/plain;charset=ISO-8859-1], Content-Length=[16]}
     Content type = text/plain;charset=ISO-8859-1
             Body = my response body
    Forwarded URL = null
   Redirected URL = null
          Cookies = []


Using Backing/Command Object

public class User implements Serializable {
    private Long id;
    private String name;
    private String password;
    private String emailAddress;

    //getters and setters
}




The Controller

@Controller
@RequestMapping
public class MyController {

   @RequestMapping("/user")
    public ResponseEntity<String> handleUserRequest (RequestEntity<User> requestEntity) {
        User user = requestEntity.getBody();
        System.out.println("request body: " + user);
        System.out.println("request headers " + requestEntity.getHeaders());
        System.out.println("request method : " + requestEntity.getMethod());

        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.put("Cache-Control", Arrays.asList("max-age=3600"));

        ResponseEntity<String> responseEntity = new ResponseEntity<>("my response body",
                                                                     headers,
                                                                     HttpStatus.OK);
        return responseEntity;
    }
}



Unit Test

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class ControllerTest {

    @Autowired
    private WebApplicationContext wac;
    private MockMvc mockMvc;

    @Before
    public void setup () {
        DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
        this.mockMvc = builder.build();
    }

    @Test
    public void testUserController () throws Exception {

        MockHttpServletRequestBuilder builder =
                                   MockMvcRequestBuilders.post("/user")
                                        .header("testHeader",
                                                "headerValue")
                                        .contentType(MediaType.APPLICATION_JSON)
                                        .content(createUserInJson("joe",
                                                            "joe@example.com"));
        this.mockMvc.perform(builder)
                    .andExpect(MockMvcResultMatchers.status()
                                                    .isOk())
                    .andDo(MockMvcResultHandlers.print());
    }

    private static String createUserInJson (String name, String email) {
        return "{ \"name\": \"" + name + "\", " +
                            "\"emailAddress\":\"" + email + "\"}";
    }
}


Output:

request body: User{name='joe', emailAddress='joe@example.com'}
request headers {testHeader=[headerValue], Content-Type=[application/json], Content-Length=[50]}
request method : POST

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /user
       Parameters = {}
          Headers = {testHeader=[headerValue], Content-Type=[application/json]}

Handler:
             Type = com.logicbig.example.MyController
           Method = public org.springframework.http.HttpEntity<java.lang.String> com.logicbig.example.MyController.handleUserRequest(org.springframework.http.RequestEntity<com.logicbig.example.User>)

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 = {Cache-Control=[max-age=3600], Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[16]}
     Content type = text/plain;charset=ISO-8859-1
             Body = my response body
    Forwarded URL = null
   Redirected URL = null
          Cookies = []



Example Project

Dependencies and Technologies Used :

  • Spring Web MVC 4.2.4.RELEASE: Spring Web MVC.
  • Spring TestContext Framework 4.2.4.RELEASE: Spring TestContext Framework.
  • Java Servlet API 3.0.1
  • JUnit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • jackson-databind 2.7.2: General data-binding functionality for Jackson: works on core streaming API.
  • JDK 1.8
  • Maven 3.0.4

Spring Request Response Entity Example Select All Download
  • spring-request-response-entity
    • src
      • main
        • java
          • com
            • logicbig
              • example
      • test
        • java
          • com
            • logicbig
              • example

See Also