Spring MVC Tutorial

Spring MVC Tutorial will helps for java developers who are about to learn spring. This tutorial is  quick start guide for  developers that uses XML based and Annotation based config .  Please go through this Spring MVC annotations tutorial for Java based config.

This tutorial has used below technologies.

  • Bootstrap  – Bootstrap for look and feel
  • Spring 4.x dependencies  –   spring 4 version libraries
  • Maven –   spring 4 and other required dependecies are configured in pom.xml files. spring 4 sample maven pom.xml file also provided in this tutorial to help project setup easily

Click here Download spring mvc annotation tutorial source code

Spring MVC is Modal View Controller that designed around Dispatcher Servlet, Handler Mappings,Controllers and View Resolver.

 Spring Dispatcher Servlet:MVC Dispatcher Servlet

  • Spring dispatcher  servlet is responsible for dispatching request to corresponding request handlers.
  • Dispatcher Servlet is HttpServlet that  configured in web.xml like below along with servlet mapping.
    •  “Spring Dispatcher”  Servlet will be invoked for each URL request that ends with “*.action”
    • Dispatcher Servlet looks for controller in handler mapping and gets the controller for URL mapping. Older versions of spring are required to configure Handler Mappings, but in new versions has  RequestMappingHandlerMapping annotation looks for @RequestMapping annotations on all @Controller.
    • Dispatcher Servlet again delegates the request to controller based on @RequestMapping Annotation values and invokes the method if any request mapping found.
    • if no mapping found then it returns 404 resource not found error.
    • Each Dispatcher Servlet has its own WebApplicationContext that extends RootAppliactionContext.
      • WebApplicationContext is Web spring container holds all MVC related beans
      • RootApplicationContext is app spring container holds all core beans such as services,dao,modal etc.
    • Dispatcher Servlet Init parameters:
      • contextClass   :   by default it used XmlWebApplicationContext
      • contextConfigLocation:   provide xml configuration  and config package path for java based config
        • provide contextConfigLocation path in init config, otherwise it will look for “spring-dispatcher-servlet.xml” in class path.
  • <servlet>
     <servlet-name>spring-dispatcher</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/config/mvcConfig.xml</param-value>
     </init-param>
     <load-on-startup>1</load-on-startup>
     </servlet>
     <servlet-mapping>
     <servlet-name>spring-dispatcher</servlet-name>
     <url-pattern>*.action</url-pattern>
     </servlet-mapping>
  •  The bellow bean configuration need to set in mvcConfig.xml to enable annotation based controller. This will scan the package and look for classes annotated with @Controller and creates bean instances. For reference, see UserController.java class below
    • <context:annotation-config />
    •  <mvc:annotation-driven />
    • <context:component-scan base-package=”org.javasavvy.controller” />

Controller:

  •  Classes that are annotated with @Controller are Spring controller
  •  In mvc config, you can define the request url mapping to vies’s with out controller mapping with  <mvc:view-controller /> tag
    • <mvc:view-controller path="/home.action" view-name="home"></mvc:view-controller>

Views and Modal:

  • Views are JSP files that returned for each request mapping.
  • View and modal  will be setup to ModalAndView object like below and returned on request method
    •  ModelAndView model = new ModelAndView();
       model.setViewName("dashboard");
       model.addObject("user",new User());
    • In above case, dashboard is jsp   ( /WEB-INF/views/dashboard.jsp) is loaded.
    • View Resolver will take care of appending  prefix(/WEB-INF/views) and suffix (.jsp) . View  Resolver also need to configure in mvcConfig.xml file
    • modal.addObject sets modal and can be accessed on JSP (dashboard.jsp) as   request.getAttribute(“user”).

Now enough of theory and let us look into Spring mvc annotation based tutorial:

  • Create Maven project:
    • Create  a new maven project File->New->Maven Project

      spring maven-application

      spring maven-application

  • Select “Create a simple project” in New Maven wizard
  • enter groupId, artifact id and select packaging type as war as hown in below pic

    Spring maven

    Spring mvc maven

  • Open the pom.xml file and add below dependencies as shown below.  Right click on project and click on  Run As -> Maven Install to trigger the build. It will load all dependency jar files into the application.
    1. <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/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <groupId>org.javasavvy</groupId>
       <artifactId>spring-mvc-tutorial</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <packaging>war</packaging>
       <properties>
              <springframework.version>4.0.6.RELEASE</springframework.version>
              <hibernate.version>4.3.6.Final</hibernate.version>
             <mysql.version>5.1.31</mysql.version>
              <joda-time.version>2.3</joda-time.version>
             <log4j.version>1.2.17</log4j.version>
             <mail.version>1.4.1</mail.version>
       </properties>
       <build>
           <finalName>spring-mvc-tutorial</finalName>
           <directory>target</directory>
           <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
           <outputDirectory>target/classes</outputDirectory>
           <resources>
                 <resource>
                    <directory>${project.basedir}/src/main/resources</directory>
                    <filtering>false</filtering>
               </resource>
            </resources>
       </build>
       <dependencies>
       <!-- Spring -->
       <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-core</artifactId>
       <version>${springframework.version}</version>
       </dependency>
       <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-context</artifactId>
       <version>${springframework.version}</version>
       </dependency>
       <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-tx</artifactId>
       <version>${springframework.version}</version>
       </dependency>
       <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-orm</artifactId>
       <version>${springframework.version}</version>
       </dependency>
       <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-web</artifactId>
       <version>${springframework.version}</version>
       </dependency>
       <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-webmvc</artifactId>
       <version>${springframework.version}</version>
       </dependency>
       <!-- Hibernate -->
       <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-core</artifactId>
       <version>${hibernate.version}</version>
       </dependency>
       <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-c3p0</artifactId>
       <version>${hibernate.version}</version>
       </dependency>
       <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-entitymanager</artifactId>
       <version>${hibernate.version}</version>
       </dependency>
       <!-- MySQL -->
       <dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
       <version>${mysql.version}</version>
       </dependency>
       <dependency>
       <groupId>org.apache.tomcat</groupId>
       <artifactId>tomcat-dbcp</artifactId>
       <version>8.0.15</version>
       </dependency>
       <!-- Joda-Time -->
       <dependency>
       <groupId>joda-time</groupId>
       <artifactId>joda-time</artifactId>
       <version>${joda-time.version}</version>
       </dependency>
       <!-- To map JodaTime with database type -->
       <dependency>
       <groupId>org.jadira.usertype</groupId>
       <artifactId>usertype.core</artifactId>
       <version>3.0.0.CR1</version>
       </dependency>
       <!-- Java Servlet -->
       <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>servlet-api</artifactId>
       <version>2.5</version>
       <scope>provided</scope>
       </dependency>
       <dependency>
       <groupId>javax.servlet.jsp</groupId>
       <artifactId>jsp-api</artifactId>
       <version>2.1</version>
       <scope>provided</scope>
       </dependency>
       <dependency>
       <groupId>jstl</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
       </dependency>
       <!-- Apapche Commons -->
       <dependency>
       <groupId>javax.mail</groupId>
       <artifactId>mail</artifactId>
       <version>${mail.version}</version>
       <exclusions>
       <exclusion>
       <groupId>javax.activation</groupId>
       <artifactId>activation</artifactId>
       </exclusion>
       </exclusions>
       </dependency>
       <dependency>
       <groupId>commons-fileupload</groupId>
       <artifactId>commons-fileupload</artifactId>
       <version>1.2</version>
       </dependency>
       <dependency>
       <groupId>commons-io</groupId>
       <artifactId>commons-io</artifactId>
       <version>1.3</version>
       </dependency>
       <!-- Google JSON -->
       <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
       <scope>compile</scope>
       </dependency>
       <dependency>
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
       <version>2.2.2</version>
       </dependency>
       <dependency>
       <groupId>org.codehaus.jackson</groupId>
       <artifactId>jackson-mapper-asl</artifactId>
       <version>1.9.10</version>
       </dependency>
       <!-- LOG4J -->
       <dependency>
       <groupId>log4j</groupId>
       <artifactId>log4j</artifactId>
       <version>${log4j.version}</version>
       </dependency>
       </dependencies>
      </project>
  • Spring Dispatcher Servlet Configuration :
    • Configure DispatcherServlet in web.xml
    • configure spring mvc context(mvcConfig.xml) as initialization parameter
    • <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
       version="2.5"> 
          <welcome-file-list>
               <welcome-file>index.html</welcome-file>
              <welcome-file>index.jsp</welcome-file>
           </welcome-file-list>
       <context-param>
            <param-name>log4jConfigLocation</param-name>
           <param-value>/WEB-INF/log4j.properties</param-value>
       </context-param>
       <listener>
            <listener-class>org.springframework.web.util.Log4jConfigListener
       </listener-class>
       </listener>
       <servlet>
           <servlet-name>spring-dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
           <init-param>
               <param-name>contextConfigLocation</param-name>
              <param-value>/WEB-INF/config/mvcConfig.xml</param-value>
            </init-param>
          <load-on-startup>1</load-on-startup>
       </servlet>
       <servlet-mapping>
            <servlet-name>spring-dispatcher</servlet-name>
            <url-pattern>*.action</url-pattern>
        </servlet-mapping>
       </web-app>
    • we configured spring-dispacher servlet with for url mappings *.action.
  • Now create our project structure that looks like below:
    • spring-mvc-folder-structure
  • Now create mvcConfig.xml that will hold the MVC model configuration
    • Controller -> UserController.java
    • View ->  /WEB-INF/views
    • Modal  – > You POJO or Value Objects
    • <context:annotation-config />  :  Enables annotation based configuration
    • component-scan :  Spring IOC scans into package and create the beans that are annotated with @RequestMapping.
    • View Resolver –   here view’s are jsp’s and need to configure prefix and suffix configuration.
    • mvcConfig.xml file:
    • <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
          <context:annotation-config /> 
           <mvc:annotation-driven />
          <context:component-scan base-package="org.javasavvy.controller" />
           <mvc:resources mapping="/resources/**" location="/resources/" />
          <bean  class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
          <bean  class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
         <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
             <property name="maxUploadSize" value="4194304" />
        </bean>
       <bean id="viewResolver"     class="org.springframework.web.servlet.view.UrlBasedViewResolver">
            <property name="viewClass"  value="org.springframework.web.servlet.view.JstlView" />
            <property name="prefix" value="/WEB-INF/views/" />
            <property name="suffix" value=".jsp" />
       </bean>
       <mvc:view-controller path="/home.action" view-name="home"></mvc:view-controller>
       </beans>
  • Finally UserController.java will look like below
    • @Controller
      @RequestMapping("/user")
      public class UserController {
      
            @RequestMapping(value="/doLogin",method=RequestMethod.POST)
             public ModelAndView doLogin(HttpServletRequest request,HttpServletResponse response){
                   ModelAndView model = new ModelAndView();
                   String email = request.getParameter("emailAddress");
                  String password = request.getParameter("password");
                  boolean error = false;
             // you validation logic goes here
              if(email!= null && password!=null && email.equalsIgnoreCase(password)){
                // If success set the view name
                   model.setViewName("dashboard");
                model.addObject("success","Authenticated successfully");
             }else{
              error = true;
       }
       if(error){
       // Returns the login view 
       model.setViewName("home");
       model.addObject("error","Invalid credentials");
       }
        return model;
        }
      }

 

This application is configured to use bootstrap css and application will look like below:

fianl-page

 

Download spring mvc maven example code from herespring-mvc-tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *