Spring MVC view controller Example

View controllers are used to forward a request to the views without any controllers written either using ViewControllerRegistry or <mvc:view-controller> element. Normally in applications view-controllers are used in static cases when there is no Controller Logic (like getting data for dropdowns) to execute before the view generates the response.

Ways to handle Spring MVC view controller

ViewControllerRegistry

ViewControllerRegistry is a registry for all the view controllers. We do not need to create a Controller class to handle requests, if we are using the ViewControllerRegistry.
You can register a view into the ViewControllerRegistry as shown below.

<mvc:view-controller> element

We can perform the same functionality as ViewControllerRegistry using the <mvc:view-controller> element. It has 2 attributes path and view-name.

Steps to Configure View Controller

1. Configuration

We have added 2 view controllers in the config file. We have also added the InternalResourceViewResolver to resolver the jsp files.

2. home and welcome.jsp

Create 2 simple jsp pages.
home.jsp

welcome.jsp

Output

When a URL is requested, it first goes to the view controllers, if it finds a matching path in the view controller, then the JSP resolver (InternalResourceViewResolver) tries to find the matching jsp for the view-name.

When we use http://localhost:8080/sampleproject we will see the home.jsp
Spring MVC view controller Example | Spring MVC Sample

When we use http://localhost:8080/sampleproject/welcome we will see the welcome.jsp
Spring MVC Tutorials view controller Example

But note that, you we do not have any view controller nor we have any Controller class for the url http://localhost:8080/sampleproject/home we will get an error.
Spring MVC Examples for Beginners