Learn about Spring MVC Framework

Learn about Spring MVC Framework

Spring MVC helps in building flexible and loosely coupled web applications. Learn how you can use the Model-view-controller design pattern to better separate business, presentation, and navigation logic in your code.

Spring MVC helps in building flexible and loosely coupled web applications. The Model-view-controller design pattern helps in seperating the business logic, presentation logic, and navigation logic. Models are responsible for encapsulating the application data. The Views render a response to the user with the help of the model object. Controllers are responsible for receiving the request from the user and calling the back-end services.

The figure below shows the flow of requests in the Spring MVC Framework.

When a request is sent to the Spring MVC Framework the following sequence of events happen.

  • The DispatcherServlet first receives the request.
  • The DispatcherServlet consults the HandlerMapping and invokes the Controller associated with the request.
  • The Controller processes the request by calling the appropriate service methods and returns a ModelAndView object to the DispatcherServlet. The ModelAndView object contains the model data and the view name.
  • The DispatcherServlet sends the view name to a ViewResolver to find the actual View to invoke.
  • Now, the DispatcherServlet will pass the model object to the View to render the result.
  • The View, with the help of the model data, will render the result back to the user.

To understand the Spring MVC Framework, we will now create a simple Hello-World example using the Eclipse IDE. I am using Eclipse IDE 3.4, Spring IDE plugin, Tomcat 6.0, and Spring 3.0 to demonstrate this example.

Go to File -> New -> Dynamic Web Project to create a web project.

 Enter the project name and click the Finish button.

 Right-click the project folder, and select Spring Tools -> Add Spring Project Nature to add Spring capabilities to the web project. This feature will be available once you install the Spring IDE.

Create a new package com.vaannila inside the src directory. The Spring controller class extends org.springframework.web.servlet.mvc.AbstractController class. To create a new controller class, right-click the src directory and create a new Java class, enter the controller class name and super class name, and then press the Finish button. 

 Copy the following code inside the HelloWorldController class.

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class HelloWorldController extends AbstractController {

    private String message;

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return new ModelAndView("welcomePage","welcomeMessage", message);
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

 The DispatcherSevlet, as the name indicates, is a single servlet that manages the entire request-handling process. When a request is sent to the DispatcherServlet, it delegates the job by invoking the appropriate controllers to process the request. Like any other servlet, the DispatcherServlet needs to be configured in the web deployment descriptor as shown.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Here, the servlet name is dispatcher. By default, the DispatcherServlet will look for a file name dispatcher-servlet.xml to load the Spring MVC configuration. This filename is formed by concatenating the servlet name ("dispatcher") with "-servlet.xml". Here, we use the the url-pattern as ".htm" in order to hide the implementations technology to the users.

The redirect.jsp will be invoked first when we execute the Spring web application. This is the only jsp file outside the WEB-INF directory, and it is here to provide a redirect to the DispatcherServlet. All the other views should be stored under the WEB-INF directory so that they can be invoked only through the controller process.

To create a bean configuration file, right-click the WebContent folder and select New -> Other. The following dialog box appears.

Select the Spring Bean Configuration file and click Next

Enter the file name as "dispatcher-servlet.xml" and click the Finish button.

Now that the Spring bean configuration file is created, we need to configure the Controller and the ViewResolver classes. The following code demonstrates how to do this.

    <bean id="viewResolver"
    class=" org.springframework.web.servlet.view. InternalResourceViewResolver" >
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <bean name="/welcome.htm" class="com.vaannila.HelloWorldController" >
        <property name="message" value="Hello World!" />
    </bean>

</beans>

First, let's understand how to configure the controller.

<bean name="/welcome.htm" class="com.vaannila.HelloWorldController" >
    <property name="message" value="Hello World!" />
</bean>

Here, the name attribute of the bean element indicates the URL pattern to map the request. Since the id attribute can't contain special characters like "/" , we specify the URL pattern using the name attribute of the bean element.

By default, the DispatcherServlet uses the BeanNameUrlHandlerMapping to map the incoming request. The BeanNameUrlHandlerMapping uses the bean name as the URL pattern. Since BeanNameUrlHandlerMapping is used by default, you need not do any separate configuration for this.

We set the message attribute of the HelloWorldController class through setter injection. The HelloWorldController class is configured just like any other JavaBean class in the Spring application context. So like any other JavaBean, we can set values to it through dependency injection (DI).

The redirect.jsp will redirect the request to the DispatcherServlet, which, in turn, consults with the BeanNameUrlHandlerMapping and invokes the HelloWorldController. The  handleRequestInternal() method in the HelloWorldController class will be invoked. Here, we return the message property under the name welcomeMessage and the view namewelcomePageto the DispatcherServlet. As of now, we only know the view name, but to find the actual view to invoke, we need a ViewResolver.

The ViewResolver is configured using the following code.

<bean id="viewResolver"
class=" org.springframework.web.servlet.view.InternalResourceViewResolver" >
    <property name="prefix">
        <value>/WEB-INF/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

Here, the InternalResourceViewResolver is used to resolve the view name to the actual view. The prefix value + view name + suffix value will give the actual view location. Here, the actual view location is /WEB-INF/jsp/welcomePage.jsp.

The following library files are needed to run the example.

antlr-runtime-3.0
commons-logging-1.0.4
org.springframework.asm-3.0.0.M3
org.springframework.beans-3.0.0.M3
org.springframework.context-3.0.0.M3
org.springframework.context.support-3.0.0.M3
org.springframework.core-3.0.0.M3
org.springframework.expression-3.0.0.M3
org.springframework.web-3.0.0.M3
org.springframework.web.servlet-3.0.0.M3

To execute the example, run the redirect.jsp file. The following page will be displayed.

Conclusion

Well, there you have it! That’s it for Spring MVC Tutorial. The code size is very less and most of the configuration is handled by Spring MVC so that we can focus on business logic.

Share & leave us some comments on what you think about this topic or if you like to add something.

spring-boot web-development

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Set up Web App with Spring Boot and Spring Security

Download the Spring Boot Web App Example Project. Run the Initial Web App. Add Project Dependencies for Your Spring Boot + Spring Security Web App. Understand Your Spring Boot App. Set Up Okta for OAuth 2.0 Single Sign-On. Configure Your Spring Boot App for Single SignOn (SSO) Refine Our Permissions

Spring Boot Tutorials - Spring Boot Full Course

Spring Boot Tutorials | Full Course - What is Spring? Spring Boot is an open source Java-based framework used to create a Micro Service. Spring Boot contains a comprehensive infrastructure support for developing a micro service and enables you to develop enterprise-ready applications that you can “just run”.

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Learn Spring Framework and Spring Boot - Build a Spring Web Application

Learn Spring Framework and Spring Boot - Build a Spring Web Application: If you're new to the Spring Framework, this is the course you want to start with. This course covers the core of the Spring Framework, the foundation which all of the other Spring Framework projects are built from.

Best Web and App Development Company in Ahmedabad

Contact DataPierce for any questions or queries you have about website development, designing, marketing projects or any small or enterprise software development.