0

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?

Vmxes
  • 2,329
  • 2
  • 19
  • 34

1 Answers1

0
@SpringBootApplication
@RestController
public class Demo1Application {

  @GetMapping
  public ResponseEntity<Student> getStudent() {

      Student stu = new Student();
      return new ResponseEntity<>(stu, HttpStatus.OK);
   }
}

@RestController will automatically make the method return that object. Default will be json if the jackson library is found in the classpath

Austin Poole
  • 652
  • 6
  • 11
  • You might be able to get away with just using [@Responsebody](https://stackoverflow.com/questions/28646332/how-does-the-spring-responsebody-annotation-work-in-this-restful-application-ex) – Austin Poole Dec 01 '18 at 15:11
  • In this simple case it is true. But I have a custom mapping and a custom handler adapter where I have to implement Spring's `HandlerAdapter` with a `handle` method that returns a `ModelAndView` – Vmxes Dec 01 '18 at 16:41