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的更多相关文章

  1. 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 @ ...

  2. Spring Boot——2分钟构建spring web mvc REST风格HelloWorld

    之前有一篇<5分钟构建spring web mvc REST风格HelloWorld>介绍了普通方式开发spring web mvc web service.接下来看看使用spring b ...

  3. [转]Spring Boot——2分钟构建spring web mvc REST风格HelloWorld

    Spring Boot——2分钟构建spring web mvc REST风格HelloWorld http://projects.spring.io/spring-boot/ http://spri ...

  4. 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架构模式,可 ...

  5. 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 ...

  6. 菜鸟学习Spring Web MVC之二

    有文章从结构上详细讲解了Spring Web MVC,我个菜鸟就不引据来讲了.说说强悍的XP环境如何配置运行环境~~ 最后我配好的环境Tomcat.Spring Tool Suites.Maven目前 ...

  7. 【Spring】Spring系列7之Spring整合MVC框架

    7.Spring整合MVC框架 7.1.web环境中使用Spring 7.2.整合MVC框架 目标:使用Spring管理MVC的Action.Controller 最佳实践参考:http://www. ...

  8. 4.Spring Web MVC处理请求的流程

  9. 1.Spring Web MVC有什么

    Spring Web MVC使用了MVC架构模式的思想,将web层进行职责解耦. 同样也是基于请求驱动的,也就是使用请求-响应模型.它主要包含如下组件: DispatcherServlet :前端控制 ...

随机推荐

  1. NDK(14)Native的char*和Java的String相互转换

    转自: http://www.cnblogs.com/canphp/archive/2012/11/13/2768937.html 首先确保C/C++源文件的字符编码是UTF-8与JAVA的class ...

  2. 在BSP的.bat文件下設置全局變量方法

    用于多個產品共用一個BSP的時候,在BSP的.bat文件中設置全局變量,去掉不需要加載的驅動和不同點是很好的方法. 一,舉例:BSP中.bat的一段code: set BSP_SMDK2443=1 s ...

  3. java 菱形

    //画菱形 一半 for(int hs=1;hs<11;hs++) //行数 { //画空格 for(int kg = 9; kg >= hs; kg--) //空格数 { System. ...

  4. TCSRM 591 div2(1000)(dp)

    挺好的dp 因为有一点限制 必须任意去除一个数 总和就会小于另一个总和 换句话来说就是去除最小的满足 那么就都满足 所以是限制最小值的背包 刚开始从小到大定住最小值来背 TLE了一组数据 后来发现如果 ...

  5. 把 HttpHandler.ashx 修改为 异步编程 异步操作

    在 ASP.NET 中,所有的处理程序类必须实现 IHttpHandler 接口或者实现 IHttpAsyncHandler 接口,这两个接口的区别是前者是一个同步接口,后者是一个异步处理模式的接口. ...

  6. ZOJ 1455 Schedule Problem(差分约束系统)

    // 题目描述:一个项目被分成几个部分,每部分必须在连续的天数完成.也就是说,如果某部分需要3天才能完成,则必须花费连续的3天来完成它.对项目的这些部分工作中,有4种类型的约束:FAS, FAF, S ...

  7. delphi 注册 dcc70.dll

    @echo 开始注册copy dcc70.dll %windir%\system32\regsvr32 %windir%\system32\dcc70.dll /s@echo dcc70.dll注册成 ...

  8. win下Velocity安装和试用

    1.eclipse等就不说了 2.velocity的eclipse插件: http://www.oschina.net/p/veloeclipse(介绍) 方法1(现在基本上非常慢)http://pr ...

  9. JAVA和C/C++之间的相互调用。

    在一些Android应用的开发中,需要通过JNI和 Android NDK工具实现JAVA和C/C++之间的相互调用. Java Native Interface (JNI)标准是java平台的一部分 ...

  10. HDU5045-Contest(状压dp)

    题意: 有n个学生,m道题,给出每个同学解出m个问题的概率,在解题过程中每个学生的解题数的差不大于1,求最大能解出题目数的期望 分析: n很小,知道用状压,但是比赛没做出来(脑子太死了,有一个限制条件 ...