Spring整合HTML學習筆記
阿新 • • 發佈:2021-02-04
技術標籤:筆記spring boot
Spring 整合HTML
Spring boot可以結合 Thymeleaf 模板整合HTML,使用原生的HTML作為檢視
Thymeleaf 模板是面向 Web 和獨立環境的 java模板引擎,它能夠處理HTML、xml、JavaScript、css等資源
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>
<groupId>org.example</groupId>
<artifactId>springboot1</artifactId >
<version>1.0-SNAPSHOT</version>
<!-- 繼承父包 -->
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.0.7.RELEASE</version>
</parent>
< dependencies>
<dependency>
<!-- web啟動jar包 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>
application.yml
server:
port: 9090
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: UTF-8
Handler
package com.makerjack.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/index")
public class IndexHandler {
@GetMapping("index")
public String index(){
return "index";
}
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
如果希望客戶端可以直接訪問HTML資源,將這些資源放置在static路徑下即可(resources/static/HTML檔名),否則必須通過Handler後臺對映才可以訪問