Gradle - Spring 4 MVC Hello World Exemple

Gradle - Exemple Spring 4 MVC Hello World

gradle-spring-logo

Dans ce tutoriel, nous allons vous montrer un MVC Gradle + Spring 4, Hello World Example (vue JSP), configuration XML.

Technologies utilisées:

  1. Gradle 2.0

  2. Spring 4.1.6.RELEASE

  3. Eclipse 4.4

  4. JDK 1.7

  5. Logback 1.1.3

  6. Boostrap 3

1. Structure du projet

Téléchargez le projetsource code et vérifiez la structure des dossiers du projet:

spring4-mvc-gradle-project

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

Trucs liés à Spring MVC.

3.1 Spring Controller – @Controller and @RequestMapping.

WelcomeController.java

package com.example.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.example.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 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.example.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. Une page JSP simple pour afficher le modèle, et inclut les ressources statiques telles que css et 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"%>



Gradle + Spring MVC









${title}

Hello ${msg} Welcome Welcome!

Learn more

Heading

ABC

View details

Heading

ABC

View details

Heading

ABC

View details


© Mkyong.com 2015

3.4 Logging – Send all logs to console.

logback.xml



    
      

        
        %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
        

      
    

    
        
    

    
        
    

    
        
    

4. Configuration Spring XML

Fichiers de configuration XML Spring.

4.1 Spring root context.

spring-core-config.xml



    

4.2 Spring web or servlet context.

spring-web-config.xml



    

    
        
        
        
    

    

    

4.3 Classic web.xml

web.xml



    Gradle + Spring MVC Hello World + XML
    Spring MVC web application

    
    
        hello-dispatcher
        
                        org.springframework.web.servlet.DispatcherServlet
                
        
            contextConfigLocation
            /WEB-INF/spring-mvc-config.xml
        
        1
    

    
        hello-dispatcher
        /
    

    
    
        
                  org.springframework.web.context.ContextLoaderListener
                
    

    
        contextConfigLocation
        /WEB-INF/spring-core-config.xml
    

5. Demo

5.1 The gradle.build file is defined an embedded Jetty container. Problèmegradle jettyRun pour démarrer le projet.

Terminal

your-project$ gradle jettyRun

:compileJava
:processResources
:classes
:jettyRun
//...SLF4j logging

> Building 75% > :jettyRun > Running at http://localhost:8080/spring4

spring-4-mvc-gradle-demo1

spring4-mvc-gradle-demo2

6. Fichier WAR

Pour créer un fichier WAR pour le déploiement:

Terminal

your-project$ gradle war

Un fichier WAR sera créé dans le dossierprojectuild\libs.

${Project}\build\libs\spring-web-gradle-xml.war

Télécharger le code source

Téléchargez-le -spring4-mvc-gradle-xml.zip (61 Ko)