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?
答案 0 :(得分:2)
基于andrearro88's answer,我做了这个通用功能,可以将ResponseEntity
复制到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());
}