In my Spring Boot 2 project I use custom handler mapping and handler adapter to select the appropriate handler method. It works fine in case of simple Controllers. However, I don't know how to handle REST Controllers properly.
I mean the custom handler adapter implements the HandlerAdapter
, that has a handle
method with a return type of ModelAndView
. But in case of a RestController
I would like to return with a data object.
I can get it work as you can see below but it is an ugly solution and has problems when using with Spring Projection
. In the code MyResponseData
is a simple DTO I want to return in json format.
@Override
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) {
response.setContentType("application/json;charset=UTF-8");
MyResponseData resp = fillResponse();
try {
Gson gson = new Gson();
String json = gson.toJson(resp);
response.getWriter().append(json);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
How can I just simply return my data represented by the MyResponseData
DTO?