[Java] [Practice! ] Display Hello World in Spring Boot

2 minute read

1. Prior knowledge

As prior knowledge, the contents of the above link are required.

2. Preparation

01.png

  1. Start Eclipse. 02.png
  2. Select [Window]→[Open Perspective]→[Other]. 03.png
  3. Select JavaEE and click the Open button. 04.png
  4. Select [Help(H)]→[Eclipse Marketplace(M)...]. : 05.png
  5. Install Spring Tools 4 (aka Spring Tool Suite 4) 4.7.0.RELEASE.

3. Creating a Spring Boot project

folder structure


Hello
└─ src
     └─ main
          ├─ java
          │ └─ com
          │ └─ example
          │ └─ demo
          │ ├─ HeloController.java
          │ └─ HelloApplication.java
          └─ resources
               ├─ application.properties
               │
               ├─ static
               └─ templates
                    └─ index.html

HeloController.java


package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HeloController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
        model.addAttribute("message", "Hello Springboot");
        return "index";
    }
}

index.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Hello</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <h1>Hello World</h1>
    <p>
      <span th:text="${message}"></span>!!!
    </p>
  </body>
</html>

06.png

  1. Select [File]→[New]→[Spring Starter Project]. 07.png
  2. Enter Hello in the name and click the Next > button. 08.png
  3. Select [Template engine]→[Thymeleaf] and [Web]→[Spring Web], and click the Finish button. : 09.png
  4. Right-click on com.example.demo and select [New(N)]→[Class]. 10.png
  5. Enter HelloController for the name and click the Finish button. 11.png
  6. Right-click on templates and select [New(N)]→[Other]. 12.png
  7. Select [Web]→[HTML file] and click the Next button. ‥ 13.png
  8. Input index.html in File name (M) and click the Finish button. ‥ 14.png
  9. Right-click on Hello [boot] and select [Run]→[5 Maven install]. *HelloController.java and index.html are listed above. 15.png
[INFO] ----------------------------------------------- -------------------------
[INFO] BUILD SUCCESS
[INFO] ----------------------------------------------- -------------------------
[INFO] Total time: 4.125 s
[INFO] Finished at: 2020-07-05T21:50:22+09:00
[INFO] ----------------------------------------------- -------------------------
  1. Success if the above statement is displayed on the console. ‥ 16.png
  2. Right-click Hello [boot] and select [Run]→[9 Spring Boot application]. 17.png
  3. Access localhost:8080 and if it looks like the image, you are successful.