简体   繁体   中英

Multiple Return Types From Single Spring MVC Controller

I have a Controller, and in some cases it should return a ResponseEntity<> if the request is Restful and in some cases should return a ModelAndView .

Is there a way this can be done? I was thinking i could throw an exception depending on what return type is required, and then have an ExceptionHandler return the exact type required.

For example, throw a ReturnResponseEntityException and then catch this in the ExceptionHandler and return a ResponseEntity , and throw a ReturnModelAndViewException in the other case.

However, i realized this would not work as the ModelAndView and ResponseEntity require certain attributes which are only available in the original Controller and not in the Exception Handlers. Is there a way to pass attributes onto exception handlers?

Alternatively, is it possible to just return Object from a Controller, and Spring will be able to process a ResponseEntity or ModelAndView depending on the class of Object i return?

Or is there another way to achieve this?

Assuming you're using Spring 4.2.x, you can use MappingJacksonValue as a return type of the REST endpoint method of your MVC controller. MappingJacksonValue is a wrapper object around java.lang.Object and you can literally wrap anything inside it, turning its content into JSON is handled by Spring. I use it for dynamic filtering of what i'm returning - the choice is based on URL parameters, during runtime and can be different for each request. Wrapping your response is easy:

    MyResponseObject response = createResponseObject();
    final MappingJacksonValue result = new MappingJacksonValue(response);
    result.setFilters(createFilters(response));
    return result;

In my opinion MappingJacksonValue is one of the greatest additions to Spring done lately!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM