Gradle – Spring 4 MVC Hello World Example
In this tutorial, we will show you a Gradle + Spring 4 MVC, Hello World Example (JSP view), XML configuration.
Technologies used :
- Gradle 2.0
- Spring 4.1.6.RELEASE
- Eclipse 4.4
- JDK 1.7
- Logback 1.1.3
- Boostrap 3
1. Project Structure
Download the project source code and review the project folder structure :

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

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

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
Gradle – Spring 4 MVC Hello World Example的更多相关文章
- Gradle – Spring 4 MVC Hello World Example – Annotation
In this tutorial, we will take the previous Gradle + Spring MVC XML example, rewrite it to support @ ...
- Spring Boot——2分钟构建spring web mvc REST风格HelloWorld
之前有一篇<5分钟构建spring web mvc REST风格HelloWorld>介绍了普通方式开发spring web mvc web service.接下来看看使用spring b ...
- [转]Spring Boot——2分钟构建spring web mvc REST风格HelloWorld
Spring Boot——2分钟构建spring web mvc REST风格HelloWorld http://projects.spring.io/spring-boot/ http://spri ...
- Spring Framework------>version4.3.5.RELAESE----->Reference Documentation学习心得----->Spring Framework中的spring web MVC模块
spring framework中的spring web MVC模块 1.概述 spring web mvc是spring框架中的一个模块 spring web mvc实现了web的MVC架构模式,可 ...
- spring 3 mvc hello world + mavern +jetty
Spring 3 MVC hello world example By mkyong | August 2, 2011 | Updated : June 15, 2015 In this tutori ...
- 菜鸟学习Spring Web MVC之二
有文章从结构上详细讲解了Spring Web MVC,我个菜鸟就不引据来讲了.说说强悍的XP环境如何配置运行环境~~ 最后我配好的环境Tomcat.Spring Tool Suites.Maven目前 ...
- 【Spring】Spring系列7之Spring整合MVC框架
7.Spring整合MVC框架 7.1.web环境中使用Spring 7.2.整合MVC框架 目标:使用Spring管理MVC的Action.Controller 最佳实践参考:http://www. ...
- 4.Spring Web MVC处理请求的流程
- 1.Spring Web MVC有什么
Spring Web MVC使用了MVC架构模式的思想,将web层进行职责解耦. 同样也是基于请求驱动的,也就是使用请求-响应模型.它主要包含如下组件: DispatcherServlet :前端控制 ...
随机推荐
- BZOJ 3142 数列(组合)
题目链接:http://61.187.179.132/JudgeOnline/problem.php?id=3142 题意:给出n,K,m,p.求有多少长度为K的序列A,满足:(1)首项为正整数:(2 ...
- Word Properties <?ref:xdo000X?> - BIP Deskotop 11.119.00.0 (32-bit) with Office 2013 (32-bit) on Win 7 64-bit
BIP Deskotop 11.119.00.0 (32-bit)Office 2013 (32-bit)Win 7 (64-bit)The current certification matrix ...
- [POJ2828]Buy Tickets(线段树,单点更新,二分,逆序)
题目链接:http://poj.org/problem?id=2828 由于最后一个人的位置一定是不会变的,所以我们倒着做,先插入最后一个人. 我们每次处理的时候,由于已经知道了这个人的位置k,这个位 ...
- createElement 创建DOM元素
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="C ...
- 关于python中使用mongodb模块,save和insert的小问题
今天写python脚本的时候发现这样一个问题: import os , string , datetime ,pymongo; conn = pymongo.Connection("127. ...
- UVa 11292 The Dragon of Loowater 勇者斗恶龙
你的王国里有一条n个头的恶龙,你希望雇佣一些骑士把它杀死(也就是砍掉所有的头).村里有m个骑士可以雇佣,一个能力值为 x 的骑士可以砍掉恶龙一个直径不超过 x 的头,且需要支付 x 个金币.如何雇佣骑 ...
- 【MySQL for Mac】终极解决——MySQL在Mac的字符集设置
这个问题烦恼一天了,现在终于得以解决.分享给大家 首先贴出来,亲测不可行的博客连接: http://www.2cto.com/database/201305/215563.html http://bl ...
- mysql的几种隐式转化
1. 表定义是字符型,传入的是Int 2. 字符集不一致.表定义的字段是gbk,传入的是utf8:这种在存储过程中出现得比较多. 数据库的字符集utf8 mysql> show create d ...
- sql server 2012序列号
MICROSOFT SQL SERVER 2012 企业核心版激活码序列号: FH666-Y346V-7XFQ3-V69JM-RHW28 MICROSOFT SQL SERVER 2012 商业智能版 ...
- window下版本控制工具Git 客户端安装
安装使用 1.下载msysgit http://code.google.com/p/msysgit/ 2.下载tortoisegit客户端安装 http://code.google.com/p/tor ...