Return type value in spring boot controllers

What is the value of the return type in spring controllers that are used to boot. Please consider the following use case:

public ModelAndView execute(final HttpServletRequest request, final HttpServletResponse response) {
    try {
        //some code.
    } catch {
        //handle the exception and build a error model and view. This model and view
        //gives a lot of freedom for error handling in case of download fails on the
        //same page without change in URL(enabling refresh of the same page again 
        //and again)
        return modelAndView;
    }
    return null;
}

      

but generally i have seen controllers with empty return types that would look like below

    public void execute(final HttpServletRequest request, final HttpServletResponse response) {
    try {
        //some code.
    } catch {
        //handle the exception but you cannot display the error with out leaving the same page. Error embedding is not possible without changing the URL.
    }
}

      

I have two questions:

a) Do they have any disadvantages of one approach to another. I see there are more use cases used first than the second.

b) Is there a flaw in returning null

instead of ModelAndView.

Literature:

Loading file from spring controllers

Error handling by redirection in spring file controller

+3


source to share


1 answer


Nothing wrong with the method of labeling like void

. You are handling the upload action via HttpServletResponse

. There are suggestions that FileSystemResource

are cleaner, but take into account that, for example, there are times when you need to send your data to another location in order to generate a report elsewhere.

Also Spring makes it easy to handle exceptions, even if your return type is in the controller void

:

@RequestMapping(value = "/pdf-report/{id}.pdf", method = RequestMethod.GET)
public void downloadPdfReport(@PathVariable String id, HttpServletRequest req, HttpServletResponse resp) throws Exception {

    //supposed logic here
    //if we are failing here then
    throw new UserFriendlyException("Cannot produce data");
}

      



Then it ControllerAdvice

plays a role:

@ControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(UserFriendlyException.class)
    public ModelAndView handleUserFriendlyException(UserFriendlyException ex) {
        //handle here your custom error page
    }
}

      

More on this from Spring resources

+2


source







All Articles