A Spring MVC tutorial for beginners showing how to use STS and Gradle to build a simple web app

Abstract

This Spring Framework tutorial shows how to build a simple Spring MVC project with gradle and STS.
SpringSourcery Content Score : 1 points  posted on  03/09/2011

Introduction

The purpose of this tutorial is to show how to use Gradle and STS to build a simple hello world Spring MVC application.

First install java and Gradle on your PC.

Gradle is a tool that is used to simplify the build, test and release process of an application. It makes building Spring MVC applications particularly easy as it downloads all of the Spring dependencies (jars) and creates a spring build file for you.

I have already written a tutorial showing how to install gradle at this link.  http://www.springsourcery.org/springSourcery/app/viewBlog/1/2/CACHEY,viewContent,1,2

I would suggest that you read this before carrying on.

Once you have gradle up and running the next task is to create a directory structure for the web application.

Create the directory structure for the project.

The project is called helloWorld.

Within the folder where you store your spring projects, create the following directories (This is normally the directory where you create your workspace).

The webapp directory is used to store the Spring configuration and JSP's that will make up the user interface.

The resources directory is used to store any properties files, for example log4j.

The java folder is used to hold all of the source code.

Note that at the same level as the main folder you should create a folder called test where all of your unit tests should go.

Now create the Gradle build file.

The gradle build file manages all of the Spring dependencies, builds the project into a web application (war file) and manages the release process.

The gradle build file should be located in the root directory of your project (in this case the helloWorld) folder.

The file should be saved as build.gradle.  This is the contents of my gradle build file.

apply plugin : 'war'
apply plugin : 'eclipse'
springVersion = "3.0.6.RELEASE"
sourceCompatibility = 1.6
slf4jVersion = "1.6.1"
group = 'com.springsourcery.helloWorld'
version = '1.0'
repositories {
mavenCentral()
}
dependencies{
compile "org.slf4j:jcl-over-slf4j:$slf4jVersion","org.slf4j:jul-to-slf4j:$slf4jVersion"
compile "org.springframework:spring-webmvc:$springVersion"
compile "javax.servlet:servlet-api:2.5"
compile "javax.faces:jsf-api:1.2_02"
compile "javax.faces:jsf-impl:1.2-b19"
compile "javax.servlet:jstl:1.1.2", "taglibs:standard:1.1.2"  
runtime "org.slf4j:slf4j-log4j12:$slf4jVersion"
testCompile "junit:junit:4.8.2"
testCompile "org.springframework:spring-test:$springVersion"
}

Once you have saved the build file, open a command prompt, navigate to the helloWorld folder (The root folder of your project where you stored the gradle.build file) and type gradle cleanEclipse eclipse.

Gradle will now start downloading all of the Spring Jar files and set about creating a STS project file. The first time you run gradle it can take a few minutes to do this.

The next screen shot shows a completed gradle build.

Next import the project into the Spring STS development environment.

You now have a Spring web project and need to import it into the STS development environment.

Load Spring STS and from the file menu (top left menu)  select the import option.

From the import menu select "Existing Projects into WorkSpace".

Click next and then navigate to the root directory of your project (the directory that you created earlier) and click finish.

This will import the project that gradle created into STS.

You now have a Spring MVC web project within your Spring STS environment.

Next create the simple Spring application.

This simple application just prints hello to the screen.

It is made up of one MVC controller and one JSP.

I tend to use the navigator view. You can access this by clicking on the

 

 icon at the bottom left of the Spring STS screen.

Within the java directory that you created earlier create the com, springsourcery and helloWorld folders (You do this by right clicking on a folder and selecting the new folder option).

Navigate into the helloWorld folder and select the new option and then the class option to create a new class for our controller.

Enter the class name (in this case HelloWorldController.class)  then click on Finish.  This will create a new class file within the helloWorld folder.

This is the code that I used to build the controller.  All it does is redirect all get requests to a jsp called hello.

package com.springsourcery.helloWorld;

import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/helloWorld")
public class HelloWorldController {

@RequestMapping(method = RequestMethod.GET)
public String showHello(Model model, HttpServletRequest request) {
return "hello";
}
}

Now create the JSP.

Within STS navigate to the jsp directory (within the webapp and WEB-INF directories) and create a new file called hello.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>helloWorld</title>
</head>

<body>
<h1>hello.</h1>
</body>
</html>

Now set-up the spring configuration for this project.

Within STS navigate to the to the WEB-INF directory (under the webapp directory).

Create a new file called web-application-config.xml.

<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<mvc:annotation-driven/>

<!-- Scan for annotation based controllers -->
<context:component-scan base-package="com.springsourcery" />

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

Now set-up the web.xml file.

Within the same location as the spring configuration file (WEB-INF, under webapp) create a new file called web.xml.

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<!-- The front controller of the Spring MVC Web application, responsible 
for handling all application requests -->
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/web-application-config.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
    
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Now set-up a index.jsp file

The index.jsp file should be created within the root of the webapp directory. Its job is to forward all requests to the controller.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%-- Redirected because we can't set the welcome page to a virtual URL. --%>
<c:redirect url="/app/helloWorld"/>

Finally set-up tomcat.

Download tomcat from this URL (use the zip file).

http://tomcat.apache.org/download-70.cgi

Unzip the file (I stored mine in c:\dev).

Add the servers tab to your STS configuration, you do this by clicking on the

icon at the bottom left of the STS window.

Within the Servers tab select new, and then server.

Select the apache folder, then select Tomcat v7.0 Server and click next.

Hit the browse button and navigate to the location where you unzipped the tomcat server and click Finish.

If all has gone well you should now have a screen that looks something like this.

To run the application move back to the navigator tab and right click on the top level folder (helloWorld). Select "run as" from the menu and then the "run on server" option.

Then click on Finish.

A whole load of text should appear on the console and the spring web browser should automatically load displaying our hello.jsp file.

And there you go this is our application running on tomcat.

You can download the full source and configuration for this tutorial at this URL. http://www.springsourcery.org/springSourcery/app/secured/download/helloWorld.zip/




Posted By

User SpringSourcery Score : 6
Software Development Team Leader
bet365.com
An accomplished hands on Software Architect with a can-do attitude and 10+ years experience in designing, developing and supporting mission critical software systems. A team player with a strong entrepreneurial spirit, great presentation skills and a talent for listening to requirements and transforming them into successful market leading products and systems. Security cleared to a SC level. Recently I have been building SpringSourcery in my own time to learn more about Spring and share my knowledge.

2 Comments



Content SpringSourcery Score : 0, User SpringSourcery Score : 0

Title : Quick note for Gradle 1.0-milestone-4 + users.

Posted on : 02/02/2012

If you run through the tutorial and get ready to fire up your first run of this project in Eclipse only to notice you have no option to "Run As > Run on Server", then try updating the line mentioned below in the build.gradle file.

For those who have tried to run the build.gradle file above lately on a recent version of gradle, specifically since 1.0-milestone-4, you'll notice the WTP-generating code was refactored into a separate plugin called eclipse-wtp. So if you are experiencing some issues with the resulting eclipse project build when importing, and its missing support for WTP, then this update should get ya going.
change the following line..

apply plugin : 'eclipse'

to be

apply plugin : 'eclipse-wtp'
For additional information see the documentation on the Eclipse plugin




Content SpringSourcery Score : 0, User SpringSourcery Score : 6

Title : Re: Quick note for Gradle 1.0-milestone-4 + users.

Posted on : 05/02/2012

Hi Adam,

Thanks for this I'm sure lots of people will find it useful!

Cheers

Dan