Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Spring MVC, is it possible to have different return types in one request handler method?

For example, if a request succeeds, I will return a View ,if not, return a String indicating error message and set the content-type to either xml or json. And the JavaScript XHR call back methods will do the job of either redirecting to another page (View) or staying in the same page and showing error info.

Based on what I read, seems like I should use "void" as the return type for handler methods. Check this out: "void if the method handles the response itself (by writing the response content directly, declaring an argument of type ServletResponse / HttpServletResponse for that purpose) or if the view name is supposed to be implicitly determined through a RequestToViewNameTranslator (not declaring a response argument in the handler method signature)."(Spring Framework reference).

What I dont understand is what " the view name is supposed to be implicitly determined through a RequestToViewNameTranslator (not declaring a response argument in the handler method signature)" means? Any anyone give me an example?

like image 489
Bobo Avatar asked Dec 14 '25 10:12

Bobo


1 Answers

A cleaner solution is to have your normal controller method throw an exception on error, then have an @ExceptionHandler method to catch it and return the error response.

@RequestMapping("/")
public View requestHandler() throws SomeException
{
  // ...
}

@ExceptionHandler(SomeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public @ResponseBody String handleSomeException(SomeExcption ex)
{
  return ex.getMessage(); // for example
}

A MappingJacksonHttpMessageConverter used with @ResponseBody will remove the need to access HttpServletResponse directly to output JSON. Alternatively, use a MappingJacksonJsonView and a Model. The same can be done using an XML converter/view.

A RequestToViewNameTranslator will (as one might guess) translate requests into view names, if no other view name is specified. See DefaultRequestToViewNameTranslator for an example.

like image 150
OrangeDog Avatar answered Dec 16 '25 23:12

OrangeDog