CuriousMind CuriousMind - 3 months ago 7
Java Question

Ways in which Controller (in Spring MVC) can provide the view name to DispatcherServlet?

I am working on a Big project, which is Spring MVC based. The views has been implemented using JSP and JSTLs. It is really a complex project.

The way I have learn Spring MVC is totally different which is being used in the project.

Usually in books I read that the Controller class returns

ModelAndView
and it is based on what this object has,
DispatcherServlet
is able to return the correct resolver.

Is there any other way in which the Controller (in MVC part) can specify the view name, for example returning a String?

Any pointer in this regards highly appreciated.

Answer

As Spring Documentation states:

All handler methods in the Spring Web MVC controllers must resolve to a logical view name, either explicitly (e.g., by returning a String, View, or ModelAndView) or implicitly (i.e., based on conventions)

So:

Is there any other way in which the Controller (in MVC part) can specify the view name, for example returning a String?

Yes, you can just specify the view name as a String return value. Basically you can determine the view explicitly by returning:

  • A String representing the logical view name
  • An instance of ModelAndView
  • An instance of a View implementation, e.g. RedirectView