Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write ResponseEntity to HttpServletResponse?

Tags:

How to write ResponseEntity to HttpServletResponse (as it makes @ResponseBody)?

For example I have authentication success handler:

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    Map responseMap = new HashMap();
    responseMap.put("user", "my_user_name");
    ResponseEntity responseEntity = new ResponseEntity(response, HttpStatus.OK);
}

If use MappingJackson2HttpMessageConverter I have error: "Could not write content: not in non blocking mode."

Code:

HttpOutputMessage outputMessage = new ServletServerHttpResponse(response);
messageConverter.write(responseEntity, null, outputMessage);

What are the best practices of implementation handlers with HttpServletResponse?

like image 377
Alexey Savchuk Avatar asked Oct 20 '16 18:10

Alexey Savchuk


People also ask

What does ResponseEntity <?> Mean?

ResponseEntity represents the whole HTTP response: status code, headers, and body. As a result, we can use it to fully configure the HTTP response. If we want to use it, we have to return it from the endpoint; Spring takes care of the rest. ResponseEntity is a generic type.

What is the difference between ResponseBody and ResponseEntity?

ResponseEntity<> is a generic class with a type parameter, you can specify what type of object to be serialized into the response body. @ResponseBody is an annotation, indicates that the return value of a method will be serialized into the body of the HTTP response.

What is HttpServletResponse in spring boot?

The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client. The response object encapsulates all information to be returned from the server to the client.

Why do we use ResponseEntity?

ResponseEntity represents an HTTP response, including headers, body, and status. While @ResponseBody puts the return value into the body of the response, ResponseEntity also allows us to add headers and status code.


2 Answers

You can use a custom response object, convert it to a JSON string using the Jackson's ObjectMapper and write the result into the request.


Example

MyResponseObject.java

private String user;

public String getUser() {
    return user;
}

public void setUser(String user) {
    this.user = user;
}

MyAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    MyResponseObject responseObj = new MyResponseObject();
    responseObj.setUser("my_user_name");

    String json = new ObjectMapper().writeValueAsString(responseObj);

    httpServletResponse.setStatus(HttpStatus.OK.value());
    httpServletResponse.getWriter().write(json);
    httpServletResponse.flushBuffer();
}  
like image 183
andrearro88 Avatar answered Oct 01 '22 02:10

andrearro88


Based on andrearro88's answer, I have made this generic function to copy a ResponseEntity to a HttpServletResponse:

public static void populateResponse(ResponseEntity<String> responseEntity, HttpServletResponse servletResponse)
        throws IOException {
    for (Map.Entry<String, List<String>> header : responseEntity.getHeaders().entrySet()) {
        String chave = header.getKey();
        for (String valor : header.getValue()) {
            servletResponse.addHeader(chave, valor);                
        }
    }

    servletResponse.setStatus(responseEntity.getStatusCodeValue());
    servletResponse.getWriter().write(responseEntity.getBody());
}
like image 31
Haroldo_OK Avatar answered Sep 28 '22 02:09

Haroldo_OK