Spring 4 MVC Maven example

Spring 4 MVC Maven example helps to develop  MVC applications with spring Java configurations. As you all know, Spring Web MVC(Modal View Controller)  designed around  DispatcherServlet that responsible for handling requests on server.

What is DispatcherServlet?

Spring MVC framework is designed on request response modal around Dispatcher Servlet, that dispatches request to Controller and it is integrated with Spring IOC to load other spring beans.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>

 

Spring supports two types of configuration loading IOC container  to instantiate beans:

  • Java annotations  configuration :  Spring provides annotations to create configure IOC and beans. In this tutorial, we will see Spring MVC with Java annotations  configuration
  • XML bean configuration :   This is widely used in spring 3 versions.Click here to access  Spring MVC Tutorial using XML configuration -tutorial  that explained with Login Form.

Installations:

  • Eclipse Mars
  • Maven 4
  • Spring 4.3
  • Java 8

Spring 4 MVC annotations:

The following are available  spring MVC annotations in Spring 4.

  • @EnableWebMvc
  • @Controller
  • @RequestMapping
  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PathVariable
  • @Valid
  • @RequestParam
  • @RequestBody
  • @ResponseBody
  • @RestController
  • @ModalAttribute
  • @SessionAttribute
  • @CookieValue
  • @RequestHeader

Lets have a look into details of some of the annotations:

  • @EnableWebMvc     
    • enables Spring MVC configuration and  same as <mvc:annotation-driven/> tag in xml configuration.
    • It enables support for annotation based MVC, so that it scans for @Controller and @RequestMapping annotations to create request handler mappings
    • Java example
      • @Configuration
        @EnableWebMvc
        public class WebMVCConfig {
        
        }
    • XML example
      • <?xml version="1.0" encoding="UTF-8"?>
        <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:mvc="http://www.springframework.org/schema/mvc"
            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/mvc
                http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
            <mvc:annotation-driven />
        
        </beans>
  • @Controller stereotype is used to auto create spring bean rather to define in xml and playsthe role of a controller
  • @RequestMapping annotation is used to map URLs such as /home, /login.action on class or a handler method.
    • @Controller
      @RequestMapping("/user")
      public class UserController {
       @Autowired
       private final UserService userService;
       
       @RequestMapping(method = RequestMethod.GET)
       public String getLoginView() {
       return "loginView";
       }
       @RequestMapping(value="/doLogin", method = RequestMethod.POST)
       public ModalAndView doLoginAcion(HttpServletRequest request,HttpServletResponse response) {
        }
       @RequestMapping(value="/getUserInfo/{userId}", method = RequestMethod.GET)
       public Modal getUser(@PathVariable("userId") long userId {
       
       }
      
      }
  • @GetMapping  :  is  shortcut for @RequestMapping(method = RequestMethod.GET)
  • @PostMapping  : is  shortcut for @RequestMapping(method = RequestMethod.POST)
  • @PutMapping :     is  shortcut for @RequestMapping(method = RequestMethod.PUT)
  • @DeleteMapping : is  shortcut for @RequestMapping(method = RequestMethod.DELETE)

Spring 4 MVC Maven example

  1. Create Maven Project and select as simple arche type. Spring 4 MVC Annotations Example
  2. Maven configuration is :
    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.spring4-mvc</groupId>
       <artifactId>spring-mvc4-tutorial</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <packaging>war</packaging>
       <name>spring-mvc4-tutorial</name>
       <description>spring-mvc4-tutorial</description>
       <properties>
             <spring.version>4.3.6.RELEASE</spring.version>
       </properties>
       <build>
           <finalName>spring-mvc4-tutorial</finalName>
           <directory>target</directory>
           <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
           <outputDirectory>target/classes</outputDirectory>
         <pluginManagement>
          <plugins>
             <plugin>
                   <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-war-plugin</artifactId>
                   <version>3.0.0</version>
                   <configuration>
                     <packagingExcludes>WEB-INF/lib/*.jar</packagingExcludes>
                      <resources>
                        <resource>
                              <directory>${project.basedir}/src/main/resources</directory>
                              <filtering>false</filtering>
                       </resource>
                    </resources>
                   <warName>spring-mvc-tutorial</warName>
                   <failOnMissingWebXml>false</failOnMissingWebXml>
              </configuration>
            </plugin>
            <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-compiler-plugin</artifactId>
                 <version>3.2</version>
                 <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                  </configuration>
              </plugin>
       
       </plugins>
       </pluginManagement>
       </build>
       <dependencies>
           <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-context</artifactId>
              <version>${spring.version}</version>
           </dependency>
         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
         </dependency>
       <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
           <version>${spring.version}</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-web</artifactId>
          <version>${spring.version}</version>
       </dependency>
       <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-webmvc</artifactId>
       <version>${spring.version}</version>
       </dependency>
       <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
       </dependency>
       <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>javax.servlet-api</artifactId>
       <version>3.1.0</version>
       </dependency>
       <dependency>
       <groupId>javax.servlet.jsp</groupId>
       <artifactId>javax.servlet.jsp-api</artifactId>
       <version>2.3.1</version>
       </dependency>
       </dependencies>
      </project>
  3. create the project structure like below:
    • app.confg  package is to load Database, Transaction Management configuration
    • web.config package is to load MVC related configurationSpring 4 MVC Project Strcuture
  4. with web.xml :

    • web.xml is used to instantiate spring web application context
    • does web.xml required in Spring 4? Not at all, but it is useful when you do migration from spring 3 to spring 4 . Refer #5 for pure java configuration
    • Some applications may require web.xml as more readable to look what are all servlet end points, filters and other security configuration.
    •  contextClass,contextConfigLocation context params are used  in  Spring 4  to initialize web app configuration that defined with @Configuration annotation.
      • contextConfigLocation param is list of @Configuration packages. Here provide app package to load database configuration always as best practice
      • contextClass:  set to this to “org.springframework.web.context.support.AnnotationConfigWebApplicationContext” enable annotation based config
    •  <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xsi:schemaLocation="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee 
       http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> 
          <welcome-file-list>
             <welcome-file>index.html</welcome-file>
             <welcome-file>index.jsp</welcome-file>
           </welcome-file-list>
       
        <context-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </context-param>
        <context-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>org.javasavvy.tutorial.app.config</param-value>
        </context-param>
         <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
         </listener>
         <servlet>
            <servlet-name>spring-dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
              <param-name>contextClass</param-name>
              <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
            </init-param>
             <init-param>
                 <param-name>contextConfigLocation</param-name>
                 <param-value>org.javasavvy.tutorial.web.config</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>
  5. With out web.xml:

    • delete web.xml and create create WebAppIntializer class that extends WebApplicationIntializer.
    • WebApplicationIntializer will be invoked when web applications starts
    • with xml config:
      • XmlWebApplicationContext is use full in migration when here are lot of mvc config beans are exists.  see the below and set the list of mvc config file.
      •  /*XmlWebApplicationContext appContext = new XmlWebApplicationContext();
         appContext.setConfigLocation("/WEB-INF/config/dispatcherServlet-config.xml");*/
    • with java config:
      • WebMVCConfig is class in org.javasavvy.tutorial.web.config package that enables Web MVC. Refer to #7 for WebMVC code
      •  AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
         webContext.register(WebMVCConfig.class)
  6. package org.javasavvy.tutorial.web.config;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRegistration;
    
    import org.springframework.web.WebApplicationInitializer;
    import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
    import org.springframework.web.servlet.DispatcherServlet;
    
    public class WebAppIntializer implements WebApplicationInitializer {
    
     @Override
     public void onStartup(ServletContext container) throws ServletException {
     
     
     /*XmlWebApplicationContext appContext = new XmlWebApplicationContext();
     appContext.setConfigLocation("/WEB-INF/config/dispatcherServlet-config.xml");*/
     
     AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
     webContext.register(WebMVCConfig.class);
     webContext.setServletContext(container);
     ServletRegistration.Dynamic registration = container.addServlet("dispatcherServlet", new DispatcherServlet(webContext));
     registration.setLoadOnStartup(1);
     registration.addMapping("*.action");
     }
    
    }
  7. Web MVC Config:Spring Java WebMVC Config
  8. Home Controller:Spring Controller Configuraiton

 

Now deploy the applications and access the url in brower : /home.action or ./contacts.action.

Sample Configuration Summary:

Sample XML Beans initialization configuration:

<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>
    <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>
sample spring 4 web application context initialization configuration:
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee 
 http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> 
 <welcome-file-list>
 <welcome-file>index.html</welcome-file>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 
 <context-param>
 <param-name>contextClass</param-name>
 <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
 </context-param>
 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>org.javasavvy.tutorial.app.config</param-value>
 </context-param>
 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <servlet>
 <servlet-name>spring-dispatcher</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
 <param-name>contextClass</param-name>
 <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
 </init-param>
 <init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>org.javasavvy.tutorial.web.config</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>

web application context initialization with out web.xml

package org.javasavvy.tutorial.web.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class WebAppIntializer implements WebApplicationInitializer {

 @Override
 public void onStartup(ServletContext container) throws ServletException {
 
 
 /*XmlWebApplicationContext appContext = new XmlWebApplicationContext();
 appContext.setConfigLocation("/WEB-INF/config/dispatcherServlet-config.xml");*/
 
 AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
 webContext.register(WebMVCConfig.class);
 webContext.setServletContext(container);
 ServletRegistration.Dynamic registration = container.addServlet("dispatcherServlet", new DispatcherServlet(webContext));
 registration.setLoadOnStartup(1);
 registration.addMapping("*.action");
 }

}

 

Hope this helps.

Downlonad Spring MVC Maven Java Code

 

3 Comments

  1. Pingback: spring mvc tutorial,spring 4 mvc tutorial,spring mvc annotation,spring pom

  2. Vivek

    I have set up a project based on the above tutorial without xml(annotation based).
    Only index page is displayed and unable to hit the controller classes

    Reply
  3. prathap

    please help me am getting below error :

    Jan 28, 2018 12:37:41 PM org.springframework.web.servlet.PageNotFound noHandlerFound
    WARNING: No mapping found for HTTP request with URI [/userApp/users/page] in DispatcherServlet with name ‘appServlet’

    calling URL:
    http://localhost:8081/userApp/ –> working fine
    http://localhost:8081/userApp/users/page –> not working throwing 404 The requested resource is not available.

    Reply

Leave a Comment

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