Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are valid return types of a Spring MVC controller method?

I have not much experience in Spring MVC and I have the following about what are the valids return types that a controller method can return.

So I know that the user generate an HttpRequest received and handled by the DispatcherServlet that dispatch this request to a specific controller class.

A controller class is something like this:

@Controller public class AccountController {      @RequestMapping("/showAccount")     public String show(@RequestParam("entityId") long id, Model model) {         ...     }      .......................................     .......................................     ....................................... } 

So I know that each method handle a specific request and that the handled request is specified by the @RequestMapping annotation.

I also know that the method return a String object that is the logical view name (that then is resolved by the view resolver to render the view)

So, at this stage, I think that a method of a controller class returns only String object. But I am not sure of it. Maybe a method like this can return also some different kind of objects?

like image 871
Java Surfer Avatar asked Mar 31 '15 10:03

Java Surfer


People also ask

What does spring controller return?

The API will generally simply return raw data back to the client – XML and JSON representations usually – and so the DispatcherServlet bypasses the view resolvers and returns the data right in the HTTP response body.


2 Answers

There are many return types are available for Handler method which is annotated by @RequestMapping inside the controller, like :

  • ModelAndView (Class)

  • Model (Interface)

  • Map
  • String
  • void
  • View
  • HttpEntity<?> or ResponseEntity<?>
  • HttpHeaders

and much more.....See Docs

Every return type have its specific use for example: If you are using String then it means return View Name and this view name will resolved by ViewResolver. If you don't want to return any view name mention return type as void. If you want to set view name as well as want to send some data to view use ModelAndView as a return type.

Please go through the documentation you will also get to know what kind of method argument you can pass in the handler method.

like image 161
Rajeev Avatar answered Oct 05 '22 19:10

Rajeev


You have a direct answer in the doc

Take a special note of the

If the method is annotated with @ResponseBody, the return type is written to the response HTTP body. The return value will be converted to the declared method argument type using HttpMessageConverters.

When the method is annoated with @ResponseBody, the return type can be any custom type, any Java pojo, that the framework will convert to an appropriate repsentation JSON, XML or the like and write back to the response body

like image 38
Master Slave Avatar answered Oct 05 '22 19:10

Master Slave