Gradle - Spring 4 MVC Hello Worldの例

Gradle – Spring 4 MVC Hello Worldの例

gradle-spring-logo

このチュートリアルでは、Gradle + Spring 4 MVC、Hello Worldの例(JSPビュー)、XML構成を示します。

使用される技術:

  1. Gradle 2.0

  2. 春4.1.6。リリース

  3. Eclipse 4.4

  4. JDK 1.7

  5. ログバック1.1.3

  6. ブーストラップ3

1. プロジェクト構造

プロジェクトsource codeをダウンロードし、プロジェクトのフォルダー構造を確認します。

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. 春MVC

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. モデルを表示する単純なJSPページ。cssや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. Spring XML設定

Spring XML構成ファイル。

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. プロジェクトを開始するためにgradle jettyRunを発行します。

ターミナル

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. WARファイル

展開用のWARファイルを作成するには:

ターミナル

your-project$ gradle war

WARファイルはprojectuild\libsフォルダーに作成されます。

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

ソースコードをダウンロード

ダウンロード–spring4-mvc-gradle-xml.zip(61 KB)