Gradle – Spring 4 MVC Hello World Example

gradle-spring-logo

In this tutorial, we will show you a Gradle + Spring 4 MVC, Hello World Example (JSP view), XML configuration.

Technologies used :

  1. Gradle 2.0
  2. Spring 4.1.6.RELEASE
  3. Eclipse 4.4
  4. JDK 1.7
  5. Logback 1.1.3
  6. Boostrap 3

1. Project Structure

Download the project source code and review the project folder structure :

spring4-mvc-gradle-project

2. Gradle Build

2.1 Review the build.gradle file, this should be self-explanatory.

build.gradle

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse-wtp'
apply plugin: 'jetty'

// JDK 7
sourceCompatibility = 1.7
targetCompatibility = 1.7

repositories {
    mavenLocal()
    mavenCentral()
}

dependencies {
	compile 'ch.qos.logback:logback-classic:1.1.3'
	compile 'org.springframework:spring-webmvc:4.1.6.RELEASE'
	compile 'javax.servlet:jstl:1.2'
}

// Embeded Jetty for testing
jettyRun{
	contextPath = "spring4"
	httpPort = 8080
}

jettyRunWar{
	contextPath = "spring4"
	httpPort = 8080
}

//For Eclipse IDE only
eclipse {

  wtp {
    component {
      
      //define context path, default to project folder name
      contextPath = 'spring4'
      
    }
    
  }
}

2.2 To make this project supports Eclipse IDE, issues gradle eclipse :


your-project$ gradle eclipse

3. Spring MVC

Spring MVC related stuff.

3.1 Spring Controller – @Controller and @RequestMapping.

WelcomeController.java

package com.mkyong.helloworld.web;

import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.mkyong.helloworld.service.HelloWorldService;

@Controller
public class WelcomeController {

	private final Logger logger = LoggerFactory.getLogger(WelcomeController.class);
	private final HelloWorldService helloWorldService;

	@Autowired
	public WelcomeController(HelloWorldService helloWorldService) {
		this.helloWorldService = helloWorldService;
	}

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String index(Map<String, Object> model) {

		logger.debug("index() is executed!");

		model.put("title", helloWorldService.getTitle(""));
		model.put("msg", helloWorldService.getDesc());
		
		return "index";
	}

	@RequestMapping(value = "/hello/{name:.+}", method = RequestMethod.GET)
	public ModelAndView hello(@PathVariable("name") String name) {

		logger.debug("hello() is executed - $name {}", name);

		ModelAndView model = new ModelAndView();
		model.setViewName("index");
		
		model.addObject("title", helloWorldService.getTitle(name));
		model.addObject("msg", helloWorldService.getDesc());
		
		return model;

	}

}

3.2 A service to generate a message.

HelloWorldService.java

package com.mkyong.helloworld.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class HelloWorldService {

	private static final Logger logger = LoggerFactory.getLogger(HelloWorldService.class);

	public String getDesc() {

		logger.debug("getDesc() is executed!");

		return "Gradle + Spring MVC Hello World Example";

	}

	public String getTitle(String name) {

		logger.debug("getTitle() is executed! $name : {}", name);

		if(StringUtils.isEmpty(name)){
			return "Hello World";
		}else{
			return "Hello " + name;
		}
		
	}

}

3.3 Views – JSP + JSTL + bootstrap. A simple JSP page to display the model, and includes the static resources like css and js.

/WEB-INF/views/jsp/index.jsp

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Gradle + Spring MVC</title>

<spring:url value="/resources/core/css/hello.css" var="coreCss" />
<spring:url value="/resources/core/css/bootstrap.min.css" var="bootstrapCss" />
<link href="${bootstrapCss}" rel="stylesheet" />
<link href="${coreCss}" rel="stylesheet" />
</head>

<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
	<div class="navbar-header">
		<a class="navbar-brand" href="#">Project Name</a>
	</div>
  </div>
</nav>

<div class="jumbotron">
  <div class="container">
	<h1>${title}</h1>
	<p>
		<c:if test="${not empty msg}">
			Hello ${msg}
		</c:if>

		<c:if test="${empty msg}">
			Welcome Welcome!
		</c:if>
        </p>
        <p>
		<a class="btn btn-primary btn-lg" 
                    href="#" role="button">Learn more</a>
	</p>
	</div>
</div>

<div class="container">

  <div class="row">
	<div class="col-md-4">
		<h2>Heading</h2>
		<p>ABC</p>
		<p>
			<a class="btn btn-default" href="#" role="button">View details</a>
		</p>
	</div>
	<div class="col-md-4">
		<h2>Heading</h2>
		<p>ABC</p>
		<p>
			<a class="btn btn-default" href="#" role="button">View details</a>
		</p>
	</div>
	<div class="col-md-4">
		<h2>Heading</h2>
		<p>ABC</p>
		<p>
			<a class="btn btn-default" href="#" role="button">View details</a>
		</p>
	</div>
  </div>


  <hr>
  <footer>
	<p>© Mkyong.com 2015</p>
  </footer>
</div>

<spring:url value="/resources/core/css/hello.js" var="coreJs" />
<spring:url value="/resources/core/css/bootstrap.min.js" var="bootstrapJs" />

<script src="${coreJs}"></script>
<script src="${bootstrapJs}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

</body>
</html>

3.4 Logging – Send all logs to console.

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
	  <layout class="ch.qos.logback.classic.PatternLayout">

		<Pattern>
		%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
		</Pattern>

	  </layout>
	</appender>

	<logger name="org.springframework" level="debug" 
                additivity="false">
		<appender-ref ref="STDOUT" />
	</logger>
	
	<logger name="com.mkyong.helloworld" level="debug" 
                additivity="false">
		<appender-ref ref="STDOUT" />
	</logger>
	
	<root level="debug">
		<appender-ref ref="STDOUT" />
	</root>

</configuration>

4. Spring XML Configuration

Spring XML configuration files.

4.1 Spring root context.

spring-core-config.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd ">
 
	<context:component-scan base-package="com.mkyong.helloworld.service" />

</beans>

4.2 Spring web or servlet context.

spring-web-config.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd ">
 
	<context:component-scan base-package="com.mkyong.helloworld.web" />
 
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<property name="prefix" value="/WEB-INF/views/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
 
	<mvc:resources mapping="/resources/**" location="/resources/" />
	 
	<mvc:annotation-driven />
 
</beans>

4.3 Classic web.xml

web.xml

<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">

	<display-name>Gradle + Spring MVC Hello World + XML</display-name>
	<description>Spring MVC web application</description>

	<!-- For web context -->
	<servlet>
		<servlet-name>hello-dispatcher</servlet-name>
		<servlet-class>
                        org.springframework.web.servlet.DispatcherServlet
                </servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring-mvc-config.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>hello-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- For root context -->
	<listener>
		<listener-class>
                  org.springframework.web.context.ContextLoaderListener
                </listener-class>
	</listener>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring-core-config.xml</param-value>
	</context-param>

</web-app>

5. Demo

5.1 The gradle.build file is defined an embedded Jetty container. Issues gradle jettyRun to start the project.

Terminal

your-project$ gradle jettyRun

:compileJava
:processResources
:classes
:jettyRun
//...SLF4j logging

> Building 75% > :jettyRun > Running at http://localhost:8080/spring4

5.2 http://localhost:8080/spring4/

spring-4-mvc-gradle-demo1

5.3 http://localhost:8080/spring4/hello/mkyong.com

spring4-mvc-gradle-demo2

6. WAR File

To create a WAR file for deployment :

Terminal

your-project$ gradle war

A WAR file will be created in project\build\libs folder.

 
${Project}\build\libs\spring-web-gradle-xml.war

Download Source Code

Download It – spring4-mvc-gradle-xml.zip (61 KB)

References

  1. Spring Web MVC References
  2. Gradle – EclipseWtp
  3. Gradle – Eclipse Plugin
  4. Gradle – War Plugin
  5. Gradle – Jetty Plugin

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Sukma Wardana
Guest
Sukma Wardana

Hi Mkyong, I’m new in Spring and your tutorial is cool. But may I ask why you make spring-mvc.xml and spring-core.xml? Can we put both configuration in one xml file?
Thanks

Gusti Arya
Guest
Gusti Arya

Hi mkyong, please make tutorial about master layout and partial layout in Spring MVC

cyberglad
Guest
cyberglad

Very cool project, but I have only 1 problem: it doesn’t work. The server doesn’t find the app entry (resource not available). Web.xml and Spring configs copied 1 to 1 from your site.Any thoughts?

James Chang
Guest
James Chang

Thanks so much. It’s helpful.

skloke
Guest
skloke

I don’t understand why view -> jsp -> index.jsp file and directory structure is under WEB-INF? Is this normal practice? Thank you (and thank you for all your tutorials).

vvvvlllll
Guest
vvvvlllll

Yes, this is normal practice. Usually WEB-INF folder is hidden for accessing on server from file manager, for example, but accessible from application. It’s trick for increase security.

Shan
Guest
Shan

Why do you need to config web and core files. Cant it work with only one?

Joe Herrera
Guest
Joe Herrera

its not really crucial, but you have a few typos on `index.jsp` here and also in the github repo.
near the bottom, both urls for

should point at the js directory instead. eg:

and finally the jquery script should be included before bootstrap at least, and hello.js probably also.

great demo and article though :)

ohadr dev
Guest
ohadr dev

great, as always. thanks!

but what happens if I wanna pass an object rather than a simple string?

SomeObj myObject = new SomeObj();…
model.addObject(“obj”, myObject)

Kisna
Guest
Kisna

Wonder why the annotation-driven should go in the bottom? especially when you customize message converters or negotiation managers, otherwise duplicate instances of RequestMappingHandlerAdapter are created?

Vivek
Guest
Vivek

Will this work with Tomcat server ?

zak
Guest
zak

Thanks. I have created an article on How to generate Rest Sevices Documentation using Swagger, maybe it can help somebody: http://opentechcode.blogspot.com/2015/09/generating-rest-services-documentation.html

uck
Guest
uck

thanks, it help me up!

RockStarInTheFuture
Guest
RockStarInTheFuture

Seriously If I could meet you someday, I’ll pay you some wines ;) . Thanks

kelgel
Guest
kelgel

Can you do a Spring MVC tutorial with multiple pages to show how to integrate a web app?

Surobinda Mallick
Guest
Surobinda Mallick

hi mkyong,

In this example u have mentioned spring-mvc-config.xml in contextConfigLocation, is it the correct file name or it is suppose to be spring-web-config.xml?

jaycuse
Guest
jaycuse

What matters is you use the same name in your web.xml file for the contextConfiguration

contextConfigLocation
/WEB-INF/spring-web-config.xml

web or mvc will do. But yeah I got confused for a second on that one to.

Amao
Guest
Amao

Correction on jsp: the tag is missing.

Harsh Singh
Guest
Harsh Singh

hi I tried to import your project zip its giving error in jsp page i.e Http javx servlet not found. However after compilation it running fine, is there is way to remove that problem

Praveen
Guest
Praveen

Add in Gradle File : compile ‘javax.servlet:javax.servlet-api:3.1.0’

Harsh Singh
Guest
Harsh Singh

thanks , i done the same.

trackback
Spring MVC hello world annotation example

[…] Gradle + Spring 4 MVC Hello World […]

trackback
Spring MVC hello world example

[…] Gradle + Spring 4 MVC Hello World […]

trackback
Spring 3 MVC hello world example

[…] Spring 4 MVC Try this Spring 4 MVC hello world example. […]

trackback
Gradle – Spring 4 MVC Hello World Example – Annotation

[…] this tutorial, we will take the previous Gradle + Spring MVC XML example, rewrite it to support pure JavaConfig and Annotation configuration, no more XML […]

syed
Guest
syed

hi can u please pu whole source code as eclipse project ..

mkyong
Guest
mkyong

Download the project, and issue “gradle eclipse”, it will generate Eclipse project files automatically.

parvez
Guest
parvez

Hi,
I want know how to integrate wily with spring boot, is there any plugin available for this.

mkyong
Guest
mkyong

Sorry, don’t like Spring Boot, try the official Spring boot document – http://projects.spring.io/spring-boot/

S?n Tr?n Thanh
Guest
S?n Tr?n Thanh

the similar this example, but into pages folder, i have 2 folder other is hello and news. in this case, how i will config in mvc-dispatcher-servlet.xml file. you can download this example from link https://www.mediafire.com/?gl1ockik3gkmqkx
could you help me please..
thanks so much!!

mkyong
Guest
mkyong

Article is updated, please review.

Rey
Guest
Rey

hey i just tried you example but for me its not working…when i am running i am getting the exception
WARNING: No mapping found for HTTP request with URI [/SpringMVC/hello/mkyong] in DispatcherServlet with name ‘mvc-dispatcher’
Can you help me how to resolve it

mkyong
Guest
mkyong

/SpringMVC/ should be your project name or context root.

Cheng
Guest
Cheng

Hi, I just met the same problem, I import this project SpringMVC to my eclipse. So my project name is SpringMVC, right? and I still get the exception.

WARNING: No mapping found for HTTP request with URI [/SpringMVC/hello/mkyong] in DispatcherServlet with name ‘mvc-dispatcher’

Could you please help me out?
Thanks

Saad Jutt
Guest
Saad Jutt

In his sample project, the project name is “GradleSpringMVC” not “SpringMVC”

So use this uri to access if you are using sample project by mkyong
http://127.0.0.1:8080/GradleSpringMVC/hello/mkyong

praveen
Guest
praveen
mkyong
Guest
mkyong

Article is updated, hardcoded a context path, try this – http://localhost:8080/spring4/

Samir Thapa
Guest
Samir Thapa

– first installed gradle
– in Spring Tool Suite imported as gradle project ( click build model)
– in STS server (vm fabric), cleaned server, add module, started
Then http://localhost:8080/spring4/ worked

Thanks mkyong!

noname
Guest
noname

Nice post!

mkyong
Guest
mkyong

Thanks.

Ram
Guest
Ram

Very quick introduction

mkyong
Guest
mkyong

Thanks, article is updated.