Posted by & filed under Content - Highlights and Reviews, Web Development.

Spring MVC provides a flexible environment for building simple, yet powerful Java Web applications. Its framework includes a wide array of configurable infrastructure and components, which can be put together to serve anything from rich Web applications to RESTful Web services. Though this can seem overwhelming at the start of a new project, getting started with Spring MVC is quite simple. This article will show how to bootstrap a basic Spring MVC application from scratch.

The source code for this article is available at: https://github.com/JamesEarlDouglas/spring-mvc-bootstrap.

Background

The MVC in Spring MVC stands for Model-View-Controller, a design pattern popularized in the book Design Patterns by the Gang of Four. The MVC pattern makes for a handy way to reason about Web applications, which can be conceptually modularized into data, transformations on data, and representation of data.

In a Spring MVC application, an HTTP request submitted by a Web browser triggers a controller method, which interacts with the application in some arbitrary way, produces a model representing some data, and names a view which knows how the data should be presented to the user.

To learn more about using Maven with Spring, be sure to look at Chapter 2 in the Pro Spring 3 title in Safari Books Online.

Build system

This project uses Maven 2 for project management, dependency resolution, code compilation, packaging, and deployment testing. Maven configuration is contained in the pom.xml file at the root of the project, and is used by the mvn program in combination with various commands:

  • Compile: mvn compile
  • Package as a WAR file: mvm package
  • Run within an embedded Jetty server: mvm jetty:start
  • Generate Eclipse project configuration: mvn eclipse:eclipse

Project structure

By convention, a Maven project is composed of a set of folders to manage source code, Web application content, and configuration. This project includes Java source code in the src/main/java folder and Web application content in the src/main/webapp folder. The pom.xml file contains the line war, which sets up Maven’s the expectation of these folders.

Web application structure

A Spring MVC application follows the conventional Java Web Application structure. Starting within a WEB-INF directory, this includes the Java Web Application Deployment Descriptor file web.xml, an optional lib directory containing library dependencies, and an optional classes directory containing compiled Java classes.

Spring MVC is configured through a Front Controller called DispatcherServlet, which is initialized by a Java Web application server based on the configuration in web.xml. In order to enable Java configuration, DispatcherServlet needs to be set to use an AnnotationConfigWebApplicationContext, directed to the Java configuration class.

Spring configuration

Historically, developing a Spring application meant working with XML configuration, which tends to become tedious to maintain, and fragile to refactor. In recent versions, support for Java configuration has taken an increasing proportion of the configuration burden, and the community has been eager to migrate away from XML configuration. In this article, Spring XML configuration will be left behind and Spring 3.1 will be used with full Java configuration support.

A Spring Java configuration class is annotated with @Configuration, and includes methods annotated with @Bean, which build up the components of the application. Spring MVC infrastructure is enabled by including @EnableWebMvc on the configuration class.

This configuration includes four beans: commentsService, a service-layer class to provide access to application data, indexController, a Spring MVC controller providing a root-level endpoint binding, commentsController, a Spring MVC controller providing comment-specific endpoint bindings, and viewResolver, a Spring MVC view resolver providing JSP views.

Controllers

Spring MVC controllers are responsible for binding HTTP endpoints to application logic. These bindings are configured through @RequestMapping-annotated methods in a @Controller-annotated class.

In IndexController, a single @RequestMapping-annotated method binds the root URI for HTTP GET requests to a view named redirect:comments. This uses a convention built into Spring to return an HTTP redirect to the user for the URI /comments.

When the user’s browser redirects to /comments, Spring will invoke the getComments method of CommentsController based on the method-level @RequestMapping annotation, which binds GET requests under the class-level @RequestMapping annotation, which binds requests to the /comments URI.

Models and views

A Spring MVC view is a way to render data to the user. This data is encapsulated by a Spring MVC model, and JSP bits are used to render instances of the Comment class as HTML. When a controller method returns a model and/or a view to Spring MVC, a ViewResolver will determine which view to use, and how to bind that model to the view.

The getComments method returns a model bound to the view name “comments”. Spring MVC takes this and, using the configured ViewResolver, looks for a file named /WEB-INF/views/.jsp to pass the model along to, and render as HTML. The view named by the return value of getComments is comments, so the ViewResolver will attempt to use the file /WEB-INF/views/comments.jsp to render the view.

Putting it all together

It is illustrative to examine the flow of data for a single Web request through the Spring MVC architecture.

  1. User points browser to http://localhost:8080/spring-mvc-bootstrap/
  2. Browser submits HTTP GET request
  3. Spring MVC’s DispatcherServlet intercepts the request, looks up handler
  4. Request is routed to the getIndex method of IndexController
  5. The view name redirect:comments is returned to Spring MVC
  6. Spring MVC returns an HTTP 301 (Redirect) response to the browser

This triggers the user’s browser to submit a second request.

  1. Browser submits HTTP GET request to http://localhost:8080/spring-mvc-bootstrap/comments
  2. Spring MVC’s DispatcherServlet intercepts the request, looks up handler
  3. Request is routed to the getComments method of CommentsController
  4. A list of comments is placed on the model, which is returned with the view name comments
  5. Spring MVC resolves the view as /WEB-INF/views/comments.jsp
  6. Spring MVC renders the view and returns it on the body of an HTTP 200 (OK) response

Spring MVC manages the complexity of mapping requests to controller methods, locating and rendering views, and wiring all the compnents together, making it simple to build up a Java Web application which is open to adaptation and evolution.

Safari Books Online has the content you need

Below are some Spring books to help you develop applications, or you can check out all of the Spring books and training videos available from Safari Books Online. You can browse the content in preview mode or you can gain access to more information with a free trial or subscription to Safari Books Online.

Pro Spring MVC: With Web Flow provides in-depth coverage of Spring MVC and Spring Web Flow, two highly customizable and powerful web frameworks brought to you by the developers and community of the Spring Framework.
Totally revised for Spring 3.0, Spring in Action, Third Edition is a hands-on guide to the Spring Framework. It covers the latest features, tools, and practices including Spring MVC, REST, Security, Web Flow, and more.
The release of Spring Framework 3 has ushered in many improvements and new features. Spring Recipes: A Problem-Solution Approach, Second Edition continues upon the bestselling success of the previous edition but focuses on the latest Spring 3 features for building enterprise Java applications.
Spring Batch in Action is an in-depth guide to writing batch applications using Spring Batch. Written for developers who have basic knowledge of Java and the Spring lightweight container, the book provides both a best-practices approach to writing batch jobs and comprehensive coverage of the Spring Batch framework.
Spring Web Services 2 Cookbook includes a wide variety of recipes that covers most important topics used in real-world applications. It is a well-rounded guide covering a lot of ground in the Spring Web Services domain using systematic arranged chapters and focused recipes.

Start your FREE 10-day trial to Safari Books Online

About this author

James Earl Douglas is a software developer focusing on functional Web APIs on the JVM. He has based many Java systems on Spring MVC and its ecosystem, which lead to authoring the e-book Barebones Spring MVC. James now researches similar and dissimilar approaches in Scala and Clojure.

Tags: Frameworks, java, Java Web Applications, Maven, RESTful web services, Rich Web Applications, Spring MVC,

Comments are closed.