Simple Example of Spring MVC

In this article, we will start with the Spring MVC Framework that is the most important module of Spring Framework.

Spring MVC is used for creating Web applications just like the way we create with any other technology. It helps us to create web applications in a more simple and effective way. Spring MVC as the name suggests follows the Model-View-Controller pattern. Following is the diagrammatic representation of MVC.

As we know, by MVC we understand that the Model is for business logic, View is used for showing the web page to the user, and the controller is used for handling the request in the same way Spring MVC works but it includes more layers here.

When the client sends the request, the request goes to the controller in MVC but in Spring MVC the request first goes to a Front Controller which is a Dispatcher Servlet class then this dispatcher servlet will call the respective controller using the annotation mapping (@Controller).

  • In Spring MVC, the Model is Plain Old Java Objects.
  • Views are JSP pages using JSTL.
  • The controller Part is the Dispatcher Servlet.

Dispatcher Servlet

In a Spring MVC Application, all the request goes through a Single Servlet called as Dispatcher Servlet. It is the only controller we use in the application. It receives a request and transfers them to all other components. The Following is the Diagramatic representation of Spring Diaptahcre Servlet.

  • The client sends the request
  • The request is sent to Front Controller which is a dispatcher servlet.
  • Dispatcher Servlet/Front Controller passes the request to the respective controller using annotations.
  • The controller handles the request and passes the Model and View to the dispatcher servlet.
  • Dispatcher Servlet now views the name of view using view Resolver.
  • At last, View renders the Model and Shows it.

Note: There is a ViewResolver whose responsibility is to resolve JSP Pages.

Spring MVC Example

Create a Spring Project Go to File> New > Other > Search maven > Select Maven Project > Next > Search Filter org.apche.maven.archetypes/webapp > Next > Enter Group Id & Archetype id > Finish.

Create the Project Structure as shown below:

Now, Create a pom.xml file to add all the dependencies needed for Spring MVC Configuration

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>co</groupId>
  <artifactId>SpringMVCExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.3.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.3.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.3.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.5</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>SpringMVCExample</finalName>
  </build>
</project>

Create the web.xml to configure DisptacherServlet. Web.xml is a deployment descriptor that is used by the server to map the incoming request.

  • Here, the server transfer request to Dispatcher Servlet which in turn retrieves the appropriate controller
  • The view (JSP file) is resolved by DispatcherServlet using the ViewResolver.
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>    
    <servlet-name>spring</servlet-name>    
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/Spring-servlet.xml</param-value>
    </init-param>   
    <load-on-startup>1</load-on-startup>      
</servlet>    
<servlet-mapping>    
    <servlet-name>spring</servlet-name>    
    <url-pattern>/</url-pattern>    
</servlet-mapping>  
</web-app>

Create a Spring-servlet.xml file. As we are building a Spring MVC application so we will need to store spring-related information in a file. So, it provides a file called [anyName]-servlet.xml. It contains information on configuration.

  • Here, we have used <context:component-scan> detects the annotation by package scanning.
  • It tells Spring to scan which package to search for Controller, Beans, or any component.
  • @Component, @Controller, @Repository, @Service, @Service, and etc. are ones that <context:component-scan> can detect.
  • To resolves views such as JSP, we have used InternalResourceViewResolver.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
   http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context.xsd">
   
   <!--  component scan -->
   <context:component-scan base-package="org.mvc.controller"></context:component-scan>
   
   
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/views/" />
      <property name="suffix" value=".jsp" />
  </bean>
   </beans>

Now, Create a Controller. The DispatcherServlet on receiving the request transfer the request to the controller.

  • The @Controller here defines the class as Controller in SpringMVC.
  • The @RequestMapping is used to map the URL. Here, it is ‘/’ means all the requests for this will be handled by this home() method.
  • Here, we have returned the “index” Page.
package org.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {

  @RequestMapping("/")
  public String home() {
    
    return "index";  // /WEB-INF/views/index.jsp
  }
}

Create an index.jsp page. Just Display the welcome message.

<html>
<head>
<title>Spring MVC</title>
</head>
<body>
<h1>Welcome To Spring MVC Framework!!!</h1>
</body>
</html>

Now, Deploy your application over the server and see the following output.

Thus, this is a simple example to get started with Spring MVC Framework. In the next article, we take another example to understand some more components in Spring MVC.