Spring Boot

Webアプリケーションの例です。埋め込まれたTomcat Thymeleafテンプレートエンジンとパッケージを実行可能な `JAR`ファイルとして使用しています。

使用される技術:

  1. 春のブート1.4.2.RELEASE

  2. Spring 4.3.4.RELEASE

  3. タイメレフ2.1.5.リリース

  4. Tomcat埋め込み8.5.6

  5. Maven 3

  6. Java 8

1.プロジェクトディレクトリ

次のフォルダを手動で作成します。


spring-boot-thymeleaf-hello-world-example

プロジェクトの依存関係


spring-boot-starter-thymeleaf`を宣言すると、

Spring Thymeleaf` Webアプリケーションを開発するために必要なものがすべて手に入ります。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
    http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-boot-web-thymeleaf</artifactId>
    <packaging>jar</packaging>
    <name>Spring Boot Web Thymeleaf Example</name>
    <description>Spring Boot Web Thymeleaf Example</description>
    <url>/</url>
    <version>1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- hot swapping, disable cache for template, enable live reload -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- Optional, for bootstrap -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <!-- Package as an executable jar/war -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

プロジェクトの依存関係を表示する:

$ mvn dependency:tree
[INFO]Scanning for projects...[INFO][INFO]------------------------------------------------------------------------[INFO]Building Spring Boot Web Thymeleaf Example 1.0[INFO]------------------------------------------------------------------------[INFO][INFO]--- maven-dependency-plugin:2.10:tree (default-cli) @ spring-boot-web-thymeleaf ---[INFO]org.springframework.boot:spring-boot-web-thymeleaf:jar:1.0[INFO]+- org.springframework.boot:spring-boot-starter-thymeleaf:jar:1.4.2.RELEASE:compile[INFO]|  +- org.springframework.boot:spring-boot-starter:jar:1.4.2.RELEASE:compile[INFO]|  |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.4.2.RELEASE:compile[INFO]|  |  |  +- ch.qos.logback:logback-classic:jar:1.1.7:compile[INFO]|  |  |  |  \- ch.qos.logback:logback-core:jar:1.1.7:compile[INFO]|  |  |  +- org.slf4j:jcl-over-slf4j:jar:1.7.21:compile[INFO]|  |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.21:compile[INFO]|  |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.21:compile[INFO]|  |  +- org.springframework:spring-core:jar:4.3.4.RELEASE:compile[INFO]|  |  \- org.yaml:snakeyaml:jar:1.17:runtime[INFO]|  +- org.springframework.boot:spring-boot-starter-web:jar:1.4.2.RELEASE:compile[INFO]|  |  +- org.springframework.boot:spring-boot-starter-tomcat:jar:1.4.2.RELEASE:compile[INFO]|  |  |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:8.5.6:compile[INFO]|  |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:8.5.6:compile[INFO]|  |  |  \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:8.5.6:compile[INFO]|  |  +- org.hibernate:hibernate-validator:jar:5.2.4.Final:compile[INFO]|  |  |  +- javax.validation:validation-api:jar:1.1.0.Final:compile[INFO]|  |  |  +- org.jboss.logging:jboss-logging:jar:3.3.0.Final:compile[INFO]|  |  |  \- com.fasterxml:classmate:jar:1.3.3:compile[INFO]|  |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.8.4:compile[INFO]|  |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.4:compile[INFO]|  |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.8.4:compile[INFO]|  |  +- org.springframework:spring-web:jar:4.3.4.RELEASE:compile[INFO]|  |  |  +- org.springframework:spring-aop:jar:4.3.4.RELEASE:compile[INFO]|  |  |  \- org.springframework:spring-beans:jar:4.3.4.RELEASE:compile[INFO]|  |  \- org.springframework:spring-webmvc:jar:4.3.4.RELEASE:compile[INFO]|  |     \- org.springframework:spring-expression:jar:4.3.4.RELEASE:compile[INFO]|  +- org.thymeleaf:thymeleaf-spring4:jar:2.1.5.RELEASE:compile[INFO]|  |  +- org.thymeleaf:thymeleaf:jar:2.1.5.RELEASE:compile[INFO]|  |  |  +- ognl:ognl:jar:3.0.8:compile[INFO]|  |  |  +- org.javassist:javassist:jar:3.20.0-GA:compile[INFO]|  |  |  \- org.unbescape:unbescape:jar:1.1.0.RELEASE:compile[INFO]|  |  \- org.slf4j:slf4j-api:jar:1.7.21:compile[INFO]|  \- nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:jar:1.4.0:compile[INFO]|     \- org.codehaus.groovy:groovy:jar:2.4.7:compile[INFO]+- org.springframework.boot:spring-boot-devtools:jar:1.4.2.RELEASE:compile[INFO]|  +- org.springframework.boot:spring-boot:jar:1.4.2.RELEASE:compile[INFO]|  |  \- org.springframework:spring-context:jar:4.3.4.RELEASE:compile[INFO]|  \- org.springframework.boot:spring-boot-autoconfigure:jar:1.4.2.RELEASE:compile[INFO]\- org.webjars:bootstrap:jar:3.3.7:compile[INFO]   \- org.webjars:jquery:jar:1.11.1:compile[INFO]------------------------------------------------------------------------[INFO]BUILD SUCCESS[INFO]------------------------------------------------------------------------[INFO]Total time: 1.429 s[INFO]Finished at: 2016-12-03T13:25:06+08:00[INFO]Final Memory: 20M/309M[INFO]------------------------------------------------------------------------

この `spring-boot-devtools`は、キャッシュを無効にし、ホットスワップを有効にして、開発者が常に最後の変更を見るようにします。開発に適しています。これを読んでください –

Spring Boot – 開発者ツール

Thymeleafテンプレートまたはプロパティファイルを変更して、ブラウザをリフレッシュして変更がすぐに反映されることを確認してください。

3.春のブート

3.1「@ SpringBootApplication」で注釈をつけてください。それだけです。 SpringブートWebアプリケーションを起動するには、このクラスを実行します。

SpringBootWebApplication.java

package com.mkyong;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootWebApplication {

    public static void main(String[]args) throws Exception {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }

}

3.2単純なSpringコントローラクラス。

WelcomeController.java

package com.mkyong;

import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class WelcomeController {

   //inject via application.properties
    @Value("${welcome.message:test}")
    private String message = "Hello World";

    @RequestMapping("/")
    public String welcome(Map<String, Object> model) {
        model.put("message", this.message);
        return "welcome";
    }

}

4. Thymeleafリソース静的ファイル

4.1 Thymeleafテンプレートファイルの場合は、 `src/main/resources/templates/`に入れます。

src/main/resources/templates/welcome.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot Thymeleaf Hello World Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

<link rel="stylesheet" type="text/css"
    href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/>

<link rel="stylesheet" th:href="@{/css/main.css}"
    href="../../css/main.css"/>

</head>
<body>

    <nav class="navbar navbar-inverse">
        <div class="container">
            <div class="navbar-header">
                <a class="navbar-brand" href="#">Spring Boot</a>
            </div>
            <div id="navbar" class="collapse navbar-collapse">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#">Home</a></li>
                    <li><a href="#about">About</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container">

        <div class="starter-template">
            <h1>Spring Boot Web Thymeleaf Example</h1>
            <h2>
                <span th:text="'Message: ' + ${message}"></span>
            </h2>
        </div>

    </div>
    <!--/.container -->

    <script type="text/javascript"
        src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</body>
</html>

4.2 CSSやJavascriptのような静的ファイルの場合、 `/src/main/resources/static/`に入れます。

/src/main/resources/static/css/main.css

h1{
    color:#0000FF;
}

h2{
    color:#FF0000;
}

4.3プロパティファイルについては、 `/src/main/resources/`に入れます。

/src/main/resources/application.properties

welcome.message: Hello Mkyong

  • 注** リソースを理解するには、http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-spring-mvc-static-content[Spring Boot static static content]をお読みくださいマッピング。

5.デモ

5.1 Spring起動Webアプリケーションを起動します。

project$ mvn spring-boot:run

  .   ________          __            ____ __ __
/\\/______'__ ____ __ __(__)__ ____  ____ __ \ \ \ \
( ( )\______ | '__ | '__| | '__ \/__` | \ \ \ \
 \\/ ______)| |__)| | | | | || (__| |  ) ) ) )
  '  |________| .____|__| |__|__| |__\____, |//// =========|__|==============|______/=/__/__/__/ :: Spring Boot ::        (v1.4.2.RELEASE)

2016-12-03 14:04:07.203  INFO 7180 ---[ restartedMain]com.mkyong.SpringBootWebApplication      : Starting SpringBootWebApplication on MKYONG-WIN10 with PID 7180 (C:\spring-boot\spring-boot-examples\spring-boot-web-thymeleaf\target\classes started by mkyong in C:\spring-boot\spring-boot-examples\spring-boot-web-thymeleaf)
2016-12-03 14:04:07.205  INFO 7180 ---[ restartedMain]com.mkyong.SpringBootWebApplication      : No active profile set, falling back to default profiles: default
2016-12-03 14:04:07.392  INFO 7180 ---[ restartedMain]ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@67af925a: startup date[Sat Dec 03 14:04:07 SGT 2016]; root of context hierarchy
2016-12-03 14:04:08.739  INFO 7180 ---[ restartedMain]s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-12-03 14:04:08.754  INFO 7180 ---[ restartedMain]o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-12-03 14:04:08.755  INFO 7180 ---[ restartedMain]org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.6
2016-12-03 14:04:08.827  INFO 7180 ---[ost-startStop-1]o.a.c.c.C.[Tomcat].[localhost].[/]      : Initializing Spring embedded WebApplicationContext
2016-12-03 14:04:08.827  INFO 7180 ---[ost-startStop-1]o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1439 ms
2016-12-03 14:04:08.969  INFO 7180 ---[ost-startStop-1]o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to[/]2016-12-03 14:04:08.976  INFO 7180 ---[ost-startStop-1]o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to:[/** ]2016-12-03 14:04:08.977  INFO 7180 ---[ost-startStop-1]o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to:[/** ]2016-12-03 14:04:08.978  INFO 7180 ---[ost-startStop-1]o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to:[/** ]2016-12-03 14:04:08.980  INFO 7180 ---[ost-startStop-1]o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to:[/** ]2016-12-03 14:04:09.196  INFO 7180 ---[ restartedMain]s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@67af925a: startup date[Sat Dec 03 14:04:07 SGT 2016]; root of context hierarchy
2016-12-03 14:04:09.242  INFO 7180 ---[ restartedMain]s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.mkyong.WelcomeController.welcome(java.util.Map<java.lang.String, java.lang.Object>)
2016-12-03 14:04:09.247  INFO 7180 ---[ restartedMain]s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-12-03 14:04:09.247  INFO 7180 ---[ restartedMain]s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-12-03 14:04:09.277  INFO 7180 ---[ restartedMain]o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path[/webjars/** ** ]onto handler of type[class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-12-03 14:04:09.277  INFO 7180 ---[ restartedMain]o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path[/** ** ]onto handler of type[class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-12-03 14:04:09.319  INFO 7180 ---[ restartedMain]o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path[/** ** /favicon.ico]onto handler of type[class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-12-03 14:04:09.687  INFO 7180 ---[ restartedMain]o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2016-12-03 14:04:09.724  INFO 7180 ---[ restartedMain]o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-12-03 14:04:09.781  INFO 7180 ---[ restartedMain]s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-12-03 14:04:09.787  INFO 7180 ---[ restartedMain]com.mkyong.SpringBootWebApplication      : Started SpringBootWebApplication in 2.943 seconds (JVM running for 3.325)

5.2アクセス


http://localhost:8080


spring-boot-thymeleaf-hello-world-example-output

6.実行可能なJARをビルドする

6.1プロジェクトをパッケージ化して、実行可能な `JAR`ファイルを作成します。

project$ mvn clean package

...

[INFO]------------------------------------------------------------------------

[INFO]Building Spring Boot Web Thymeleaf Example 1.0

[INFO]------------------------------------------------------------------------

...[INFO]--- maven-jar-plugin:2.6:jar (default-jar) @ spring-boot-web-thymeleaf ---[INFO]Building jar: C:\spring-boot\spring-boot-examples\spring-boot-web-thymeleaf\target\spring-boot-web-thymeleaf-1.0.jar[INFO][INFO]--- spring-boot-maven-plugin:1.4.2.RELEASE:repackage (default) @ spring-boot-web-thymeleaf ---[INFO]------------------------------------------------------------------------[INFO]BUILD SUCCESS[INFO]------------------------------------------------------------------------[INFO]Total time: 1.797 s[INFO]Finished at: 2016-12-03T14:06:45+08:00[INFO]Final Memory: 21M/437M[INFO]------------------------------------------------------------------------

6.2それを実行し、


http://localhost:8080


に再度アクセスします。

project$ java -jar target/spring-boot-web-thymeleaf-1.0.jar

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

ダウンロードする –

spring-boot-web-thymeleaf.zip

(9 KB)

参考文献

ブート – 静的コンテンツ]。

https://spring.io/blog/2014/03/07/deploying-spring-boot-applications

[Deploying

春のブートアプリケーション]。リンク://spring-mvc/spring-mvc-how-to-include-js-or-css-files-in-a-jsp-page/[Spring

ブート – 開発者ツール]。

https://spring.io/guides/gs/serving-web-content/

[ウェブコンテンツの配信

Spring MVCで]。リンク://spring-boot/spring-boot-hello-world-example-jsp/[Spring Boot

Hello Worldの例 – JSP]


埋め込みコンテナ


hello world

リンク://タグ/spring-boot/[spring
boot]

thymeleaf


tomcat