Spring MVC Application

Now we understand the concepts, and configured our Spring MVC application.

  • The DispatcherServlet delegates the request to the appropriate controller to handle the request.

  • The @Controller annotation indicates that a particular class serves as the role of a controller.

  • The @RequestMapping annotation is used to map a URL to either an entire class or a particular controller method.

The @Controller annotation inherits from @Component annotation. So, It’s a special @Component used in MVC web application, and so, it will be scanned by Spring IoC as a component.

So, now, this controller will handle all the requests for root path URL of our JbkDispatcher we’ve created.

We can pass different parameters like request, session, model objects, and return different types of objects (as you’ll see later) from controller method.

All request mapping on methods are relative to the controller mapping.

So, now, the welcome()method will handle root path of this controller.

By default, It handles all types of HTTP request (GET, POST, etc) unless explicitly defined (i.e. using method in @RequestMapping).

We mean by model here is an object that we can use to pass data around the controller methods and views.

These data is called model attribute(s), they can be java beans that carry form data for data binding.

So, we can pass a model attribute from a controller method to a view page, and then from the view page back to a controller method (i.e. when form is submitted).

The model object can be passed as a parameter to controller method so that we can add attributes, and these attributes can be accessed by the view to display the final result.

We can return a view page name, an object, or not return anything at all. In case of returning a view page name, Spring will load the view page from using this format:prefix + view page name + suffix (defined previously in “spring-mvc-demo-servlet.xml” file) to be rendered and displayed.

These are mostly the JSP pages (but you can have HTML, PDF, Excel worksheets, XML, etc). In JSP pages, you write your HTML, and use the reusable UI components (like tags) in Spring.

In our case, we need to create “welcome-page.jsp” file.

The view pages must be located in the location we’ve defined earlier in “spring-mvc-demo-servlet.xml” file.

The ${message} is the attribute which we assigned in welcome () method.

Make sure you have tomcat 8 or higher. Deploy application and run in browser. Project structure should be like this.

Spring MVC project structure

To test the project hit the URL → http://localhost:8080/[NameOfTheProject]/

See image below

MVC Project Output