spring

Spring MVC 3.0 Tutorial

Spring MVC (Model-View-Controller) is the web component of Spring framework, which provides a great functionality for building web Applications. Following the basic tenet of Spring framework “convention over configuration“, the Spring MVC Framework is designed in such a way that every piece of logic and functionality is highly configurable. Spring is not tightly coupled with Servlet or JSP technology paradigms to render the view to the clients. It is also very simple and easy to integrate Spring with other Web Frameworks. Thus Spring is a perfect and logical choice for building multi-faceted web application with multiple interfaces. Additionally, Spring MVC can also work seamlessly with third party view technologies like Velocity, Freemarker and document manipulation APIs like Apace POI, Aspose etc.

1. Spring MVC Tutorial – Introduction

MVC stands for Model-View-Controller. Like most other MVC frameworks, Spring MVC is also request-driven. The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, time zone and theme resolution as well as support for uploading files. The DispatcherServlet is completely integrated with Spring IoC container. The default handler is based on the @Controller and @RequestMapping annotations, offering a wide range of flexible handling methods.

Spring MVC Tutorial - Spring MVC architecture
Fig. 1 Spring MVC architecture

The request processing flow in Spring MVC is as follows:

  • A request is sent from the client to the web container as a http request.
  • This request is first intercepted by the DispatcherServlet,which then looks for appropriate handler mappings designated to handle that request.
  • The handler mappings contain a list of controllers. DispatcherServlet will forward the request to the correct controller.
  • The controller will process the request and send back the backing model and view object to the DispatcherServlet.
    The DispatcherServlet will then resolve the view with the help of ViewResolver mappings. This is consulted to resolve views which can be JSP, Velocity etc.
  • The final view is sent to the client and rendered on browser.

Spring MVC Tutorial -  Request Process Lifecycle
Fig. 2 Request Process Lifecycle

2. Technologies used

  1. Spring 4.2.6.RELEASE
  2. Maven 3
  3. JDK 1.8
  4. Spring Tool Suite (STS) 3.9.0
  5. Java Server Pages

3. Setup Maven project

In this tutorial, we show you a Spring MVC hello world example, using Maven build tool.
Maven dependencies: We will be using Apache Maven for our project management. The required dependencies for a Spring MVC project are added and Maven will resolve and manage all the dependencies automatically. Below is the pom.xml file for our project.

Spring MVC Tutorial - POM file
Fig. 3 POM file

We have included the maven-war-plugin since we are configuring our application using Java Configuration, we don’t need the web.xml anymore. In order for our project to build successfully, we need to instruct Maven to ignore the web.xml file. We do this by setting the failOnMissingWebXml element to false.

3.1 Create a Maven Project in Spring Tool Suite

  • Navigate to File menu in Eclipse or Spring Tool Suite IDE.
  • Click ‘File’ -> ‘New’ -> ‘Maven Project’.

Spring MVC Tutorial - Maven project
Fig. 4 Create Maven project

Under the “New Maven Project” window:

  • Select ‘Create a simple project….’ check box.
  • The remaining options can be kept as it is and simply click on ‘Next’.

Fig. 5 Create Maven 2

In the next window enter the following options:

  • For Group ID enter com.springmvccodegeeks
  • For Artifact ID enter springmvccodegeeks
  • The remaining options can be kept as it is (We will be working with a jar file here)
  • Click on ‘Finish’.

Fig. 6 Create project attributes

A new maven project is created and is visible under Package Explorer in Eclipse

Fig. 5 Final maven project structure

4. Project Demo

4.1 Setting up application configuration

In this example we are using java based configurations. These style of configurations allow for more flexibility and easier debugging capabilities. Hence we will not be using the traditional web.xml. Instead we will be implementing the org.springframework.web.WebApplicationInitializer API to spin up our application context.

SpringMvcInitializer.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    /* (non-Javadoc)
     * @see org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer#getRootConfigClasses()
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { SpringMvcConfig.class };
    }
    /* (non-Javadoc)
     * @see org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer#getServletConfigClasses()
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {     
        return null;
    }
    /* (non-Javadoc)
     * @see org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#getServletMappings()
     */
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

Here the method getRootConfigClasses() should return a class setting up the application root context. The method getServletConfigClasses() should return a class setting up the web context on top of the previously defined application context. In our example, however, to keep things simple, the root context class itself is setting up the necessary contexts. Finally, getServletMappings defines the http API endpoints to be responded by the DispatcherServlet. This can be modified to hold different string patterns.

4.2 Setting up the Spring configuration

Since we have moved away from xml-based configurations, we are creating the spring application context in java class. To setup the spring MVC configs, this java config class should extend the org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter class.

SpringMvcConfig.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.springmvccodegeeks"})
public class SpringMvcConfig extends WebMvcConfigurerAdapter {
    
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

The uses for the different annotations:
@Configuration – This annotation will tell spring application context to treat this as a configuration class during auto scanning.
@EnableWebMvc – Enable Spring MVC-specific annotations like @Controller
@ComponentScan – Scan starts from base package and registers all controllers, repositories, service, beans, etc. Include the packages here which contains beans or classes for the application to inject when required.
@Bean – Defines spring beans. Here we have defined the ViewResolver

4.3 Setting up the Controller

We are annotating the class with @Controller annotation. This annotation is a stereo type annotation used to indicate that this is a controller. This enables the DispatcherServlet to automatically map the methods defined in the class using the @RequestMapping annotation.

The @RequestMapping annotation maps the URL’s onto particular classes or methods. The class-level annotation is mostly used to map a specific request path onto a form controller, whereas a method-level annotations narrows the mapping for a specific HTTP request method like (GET, PUT, POST and DELETE). In this example, we are using the annotation at the method level. Also, we are populating the Model map. This is a map for the request attributes. It contains a key called message and a simple string value.

The return value is the name of the view. The InternalResourceViewResolver will prefix and suffix the return value to form the real path of the view file name.

DefaultController.java

1
2
3
4
5
6
7
8
9
@Controller
public class DefaultController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(ModelMap model) {
        model.addAttribute("message", "Spring MVC Java Configuration Example!!");
        return "index";
    }
}

4.4 Setting up the JSP page

We are creating a simple JSP page here. This page will be rendered as the home page when the main application endpoint is requested from a client (browser). This view will display the value of the message attribute we added earlier in the controller.

Fig. 7 index.jsp

The final project structure is as below:

Fig. 8 Final project structure

4.5 View in browser

Start the embedded application server that comes with the IDE. Open a browser and enter the URL: http://localhost:8080/springmvccodegeeks/ . The message “Spring MVC Java Configuration Example!!” is displayed as was defined in the controller method. This is a simple view rendering.

Fig. 9 View application in browser

5. Conclusion

In this example we have covered the following:

  • Understand the basic concepts and main elements of a Spring MVC project
  • Setup a simple MVC project using maven
  • Render a page and display customized message using spring MVC

6. References

7. Download the Source Code

Download
You can download the full source code of this example here: SpringMVC

Diptayan Datta

Diptayan has a bachelors degree in Electronics and Communication Engineering. He also holds a Master degree in Information Systems. In his professional career, he has worked with several organizations in both software tester and developer roles. He is currently involved as an application developer in the Tax, Accounting and Corporate Law sector where he is working with Java, Spring, Hibernate, Selenium, JavaScript and AngularJS.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
krunal gajbhye
krunal gajbhye
5 years ago

Login application in spring ———————————————————————————————— pom,xml file are 1.8 4.3.0.RELEASE 5.1.36 2.9.0 junit junit 3.8.1 test org.springframework spring-context ${spring.version} org.springframework spring-webmvc ${spring.version} org.springframework spring-web ${spring.version} org.springframework spring-orm ${spring.version} javax.servlet javax.servlet-api 3.1.0 provided javax.servlet.jsp javax.servlet.jsp-api 2.3.1 provided javax.servlet jstl 1.2 mysql mysql-connector-java ${mysqlconnector.version} Configuration file —————————————————————————- WebMvcConfig.java package com.krunal.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages=”com.krunal”) @PropertySource(value= {“classpath:application.properties”}) public class WebMvcConfig extends WebMvcConfigurerAdapter { @Autowired Environment env; @Bean public ViewResolver getViewResolver() { InternalResourceViewResolver view= new InternalResourceViewResolver(); view.setPrefix(“/views/”); view.setSuffix(“.jsp”); return view; }… Read more »

Back to top button