Added the thymeleaf starter to my Spring Boot application.
Added a @RequestMapping to my Application java file:
package com.sgbsc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@SpringBootApplication
@Controller
public class Bsc1Application {
@RequestMapping("/hello-template")
public String helloTemplate() {
return "hello-template";
}
public static void main(String[] args) {
SpringApplication.run(Bsc1Application.class, args);
}
}
Needed the @Controller to tell Spring what to return for the URL.
In Spring, a Controller is a class which is responsible for preparing a model Map with data to be displayed by the view as well as choosing the right view itself. It can also directly write into response stream by using @ResponseBody annotation and complete the request.
If we were writing a RESTful application, we’d use @RestController which is a convenience controller meaning @Controller + @ResponseBody.
This application just returns two pages:
index.html
- sent back automatically by the DispatcherServlet
- auto-configured by Spring Boot upon seeing @SpringBootApplication and Web starter in pom.xml.
- It looks for an index.html, and css under the static resources folder.
hello-template.html
- Spring Boot notices thymeleaf starter in pom.xml
- Spring’s RequestMappingHandlerMapping is used to maintain the mapping of the request URI to the handler (which are the controller methods annotated with the @RequestMapping annotation). Once the handler is obtained, the DispatcherServlet
dispatches the request to the appropriate handler adapter.
src/main/resources/static/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>bsc1</title>
<link rel="stylesheet" href="/css/bsc1.css"/>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
<link rel="icon" href="/favicon.ico" type="image/x-icon">
</head>
<body>
<h1>Hello, and welcome to a static "hello world" page!</h1>
</body>
</html>
src/main/resources/static/css/bsc1.css
@charset "ISO-8859-1";
body {
background-color: lightblue;
}
h1 {
color: white;
src/main/resources/static/template/hello-template.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>bsc1 - hello template</title>
<link rel="stylesheet" href="/css/bsc1.css"/>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
<link rel="icon" href="/favicon.ico" type="image/x-icon">
</head>
<body>
<h1>This is a Thymeleaf template!</h1>
</body>
</html>
I also used a free icon generator to make a favicon.ico and put it under src/main/resources/static too.