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 :前端控制 ...
随机推荐
- git stash 暂存当前修改
当我们在开发项目的时候,突然来一个变更需要修改,我们除了将当前项目提交(commit)后切换(checkout) 到其他分支外,我们还可以先将当前的修改暂存(stash)起来,然后再切换(checko ...
- linux 压缩/解压命令大全
.tar 解包:tar xvf FileName.tar打包:tar cvf FileName.tar DirName(注:tar是打包,不是压缩!)———————————————.gz解压1:gun ...
- HDU 4946 共线凸包
题目大意: 一些点在一张无穷图上面,每个点可以控制一些区域,这个区域满足这个点到达这个区域的时间严格小于其他点.求哪些点能够控制无穷面积的区域. 题目思路: 速度小的控制范围一定有限. 速度最大当且仅 ...
- 宏UT_LIST_ADD_FIRST
/*******************************************************************//** Adds the node as the first ...
- UVa 11427 (期望 DP) Expect the Expected
设d(i, j)表示前i局每局获胜的比例均不超过p,且前i局共获胜j局的概率. d(i, j) = d(i-1, j) * (1-p) + d(i-1, j-1) * p 则只玩一天就就不再玩的概率Q ...
- angular js 实例参数学习
<!DOCTYPE html> <html> <head> <meta name="description" content=" ...
- h264检测是I帧还是P帧,解决录像第一帧有马赛克问题
最近使用h264码流数据进行录像,但是录出来的第一帧有马赛克,究其原因是录像的第一帧不是关键帧,所以需要录像是需要判断第一帧是否是关键帧,方法有两种,第一种是原码流的基础上查找,第二种是将原码流传递给 ...
- Go2Shell 打开设置窗口
Go2Shell默认没有设置界面,需要用命令行打开 在Shell中输入: open -a Go2Shell --args config
- zoj 2770 Burn the Linked Camp (差分约束系统)
// 差分约束系统// 火烧连营 // n个点 m条边 每天边约束i到j这些军营的人数 n个兵营都有容量// Si表示前i个军营的总数 那么 1.Si-S(i-1)<=C[i] 这里 建边(i- ...
- grep的-A-B-选项详解(转)
grep的-A-B-选项详解(转)[@more@] grep能找出带有关键字的行,但是工作中有时需要找出该行前后的行,下面是解释 1. grep -A1 keyword filename 找出file ...