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. java 基础学习

    a+b: import java.util.Scanner; public class Main { public static void main(String args[]){ Scanner c ...

  2. Android wakelock机制

      Wake Lock是一种锁的机制, 只要有人拿着这个锁,系统就无法进入休眠,可以被用户态程序和内核获得. 这个锁可以是有超时的或者是没有超时的,超时的锁会在时间过去以后自动解锁. 如果没有锁了或者 ...

  3. HDU 1711 (裸KMP) Number Sequence

    题意: 用第二个数列去匹配第一个数列,输出第一次匹配到的位置,如果没有则输出-1. 分析: 这明显是一道裸的KMP. 我是在这篇博客上学的KMP算法的,讲得比较透彻. http://blog.csdn ...

  4. Content-Type

    HTTP Content-type .*( 二进制流,不知道下载文件类型) application/octet-stream .txt text/plain 没有csv这种类型

  5. apache开源项目 -- Tuscany

    tuscany是Apache组织关于SOA实现的一个开放源码的工程项目,目前处于孵化期阶段. 该项目主要基于SCA,SDO,DAS等技术上实现的. SCA 的基本概念以及 SCA 规范的具体内容并不在 ...

  6. linux面试题1

    一.填空题:1. 在Linux系统中,以 文件 方式访问设备 .2. Linux内核引导时,从文件 /etc/fstab 中读取要加载的文件系统.3. Linux文件系统中每个文件用 i节点 来标识. ...

  7. 通过userAgent判断手机浏览器类型

    我们可以通过userAgent来判断,比如检测某些关键字,例如:AppleWebKit*****Mobile或AppleWebKit,需要注意的是有些浏览器的userAgent中并不包含AppleWe ...

  8. geusture for chrome cfg

    { "name": "Chrome Gestures", "version": "1.13.4", "norm ...

  9. Storm实战常见问题及解决方案

    该文档为实实在在的原创文档,转载请注明: http://blog.sina.com.cn/s/blog_8c243ea30101k0k1.html 类型 详细 备注 该文档是群里几个朋友在storm实 ...

  10. dell optiplex台式机 安装win7 清楚分区的方法

    http://jingyan.baidu.com/article/92255446e1065f851648f42b.html