Gradle build Spring4 MVC Hello World Example

In this post we will create a simple Hello World example with Spring4 MVC. The build tool used here is Gradle.

For a Hello World example, there are almost no difference between Spring3 and Spring4, but there are external dependencies you need to care. Its OK to run Spring4 with JDK7, Spring is backward compatible, but the suggested platform for Spring 4 is JDK8, its the first-class citizen supported by Spring 4. While for Spring 3 , the maxmium JDK version is JDK7.

There are some features in Spring 4 you can only use in JDK8 because they are not present in JDK7.

If you are using JDK8, the Tomcat version should match too, you may get error if the Tomcat version is too low


Components used in this project

This example will use JDK8.

  • JDK8
  • Tomcat 7.0.68
  • Spring 4.2.2

Step 1. Create Project

Create a Gradle project with structure like this. Make sure you are using JDK8, both the JRE that run Eclipse and the JRE activated in Eclipse should be JDK8.

You may like to look at these to make sure the JDK environment is OK.

Step 2. Add Gradle build script

In this Gradle build script, we use Spring 4.2.2, Tomcat 7.0.68 and cargo plugin. There are two ways to deploy the application, using cargo tasks like cargoRunLocal, or manually start the Tomcat server but let Gradle copy WAR for you.

apply plugin: 'base'
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'jetty'
apply plugin: 'com.bmuschko.tomcat'
apply plugin: 'com.bmuschko.cargo'
ext.tomcatVersion = '7.0.68'
ext.cargoVersion = '1.1.3'
buildscript {
    repositories {
    dependencies {
        classpath 'com.bmuschko:gradle-tomcat-plugin:2.2.2'
        classpath 'com.bmuschko:gradle-cargo-plugin:2.1.1'    
repositories {
dependencies {
   providedCompile 'javax.servlet:javax.servlet-api:3.0.1'
   compile 'org.springframework:spring-webmvc:4.2.2.RELEASE'
   runtime "jstl:jstl:1.2"
   tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}", "org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}"
   tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}") {
       exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj'
       cargo "org.codehaus.cargo:cargo-core-uberjar:${cargoVersion}",  "org.codehaus.cargo:cargo-ant:${cargoVersion}"
cargo {
    containerId = 'tomcat7x'
    port = 8080
    local {
        installer {
            installUrl = "${tomcatVersion}/bin/apache-tomcat-${tomcatVersion}.zip"
            downloadDir = file("$buildDir/download")
            extractDir = file("$buildDir/extract")
        outputFile = file("container/apache-tomcat-${tomcatVersion}/output2.log")
war {   
    version = '' 
task finalize << {
    println('after build')
        from "${buildDir}\\libs"
        into "$buildDir/extract\\apache-tomcat-${tomcatVersion}\\apache-tomcat-${tomcatVersion}\\webapps"
        include '*.war'

Step 3. Configure Spring4 MVC

We use annotation based configuration, the following file equivalent to web.xml

package com.example.springcontext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.servlet.DispatcherServlet;
public class ExampleWebApplicationInitializer implements WebApplicationInitializer {
    private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
    public void onStartup(ServletContext servletContext) throws ServletException {
    private void registerDispatcherServlet(ServletContext servletContext) {
        AnnotationConfigWebApplicationContext dispatcherContext = createContext(WebConfig.class);
        ServletRegistration.Dynamic dispatcher;
        dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(dispatcherContext));
    private AnnotationConfigWebApplicationContext createContext(final Class<?>... annotatedClasses) {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        return context;

There is only one mapping, the home page, will be handled by our controller.

To configure Spring MVC, use the following file

package com.example.springcontext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
public class WebConfig {
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = 
                    new InternalResourceViewResolver();
        return resolver;

What it do is simple, tell Spring where to look for components like controllers, and how to resolve view file.

Step 4. Controller

This controller will handle the request for our home page.

package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
public class IndexController {
    public String showHomePage(Model m) {
        m.addAttribute("name", "sam");
        return "index";

It simply add an attribute to model object which can be used in view JSP file and return the view name, according our view file resolve configuration in last step, this name will be resolved to /view/index.jsp

Step 5. View

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
#textbox-style {
    width: auto!important;
    height: auto!important;
    margin: 0 auto;
    padding: 20px!important;
    border: solid rgba(255, 255, 255, .5)!important;
    border-width: 1px 0!important;
    overflow: hidden;
    text-align: left;
    font-size: 13px!important;
    line-height: 16px!important;
    background: transparent!important;
    box-shadow: 0 0 10px 5px rgba(0, 0, 0, .4)
#textbox-style .textbox-inner-style-wrap .textbox-inner-style-img {
  margin: 0!important;
  display: block;
  float: left;
#textbox-style .textbox-inner-style-wrap .textbox-inner-style-text,
#textbox-style .textbox-inner-style-poweredby {
  display: block!important;
  float: none!important;
  width: auto!important;
  height: auto!important;
  margin-left: 145px!important;
    font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif!important;
    color: white!important;
#textbox-style .textbox-inner-style-wrap .textbox-inner-style-text {
    padding-top: 0!important;
    color: rgba(255, 255, 255, .8)
#textbox-style .textbox-inner-style-poweredby {
    text-align: left!important;
    color: inherit!important;
  margin-top: 10px!important;
#textbox-style {
    width: 330px!important;
    margin: 0 auto;
    padding: 15px!important
  <div id="textbox-style"> 
       ${name} Hello World 

Step 6. Start and running

Run Gradle build with tasks :build and :war, then run catalina.bat run. Visit url http://localhost:8080/Spring4MVCExample/

See also