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. Image.FrameDimensionsList 属性备注

    Image.FrameDimensionsList 属性 .NET Framework 2.0   获取 GUID 的数组,这些 GUID 表示此 Image 中帧的维数. 命名空间:System.D ...

  2. AndroidApplication Fundamentals(Android应用基础)

    AndroidApplication Fundamentals(Android应用基础) Android应用采用Java编程语言来编写,AndroidSDK工具编译我们的代码,连同任何数据和资源文件一 ...

  3. Android开发之火星坐标转换工具

    代码: import java.io.InputStream; import java.io.ObjectInputStream; /* * 把获取到的真实地址转换为火星坐标 */ public cl ...

  4. android线程池

    线程池的基本思想还是一种对象池的思想,开辟一块内存空间,里面存放了众多(未死亡)的线程,池中线程执行调度由池管理器来处理.当有线程任务时,从池中取一个,执行完成后线程对象归池,这样可以避免反复创建线程 ...

  5. java转换json需导入的jar包说明

    commons-beanutils-1.8.0.jar不加这个包 java.lang.NoClassDefFoundError: org/apache/commons/beanutils/DynaBe ...

  6. 浏览器检测是否安装flash插件,若没有安装,则弹出安装提示

    说白了其实就是在html中前途flash的使用代码 <!--    html嵌入flash,检测浏览器是否安装flash插件,并提示安装.-->    <object type=&q ...

  7. 完整cocos2d-x编译Andriod应用过程

    作者:何卫 转载请注明,原文链接:http://www.cnblogs.com/hewei2012/p/3366969.html 其他平台移植:http://cocos2d.cocoachina.co ...

  8. AWK print学习

    Awk是一种处理结构数据并输出格式化结果的编程语言, Awk 是其作者 "Aho,Weinberger,Kernighan" 的简称. Awk通常被用来进行格式扫描和处理.通过扫描 ...

  9. 【Unity3D】枪战游戏—发射子弹、射线检测

    一.子弹的碰撞检测: 因为子弹的移动速度非常的快,那么如果为子弹添加一个collider,就有可能检测不到了. 因为collider是每一帧在执行,第一帧子弹可能在100米处,那么下一帧就在900米处 ...

  10. Informatica 9.1常用查询

    select a.mapping_name, a.mapping_id, a.subject_id, a.is_valid, b.pv_precision, c.pv_value, b.pv_defa ...