本篇博客在SpringBoot学习01--Hello world程序的基础上进行,实现SpringBoot访问HTML页面功能。
操作前先了解:
SpringBoot的Web相关文件存放在src/main/resources目录下。
一般情况下static目录用于存放静态文件,例如css、图片等文件,templates用于存放HTML文件,
如果resources目录下没有这两个目录,需要自行新建出来。
步骤:
1.添加依赖
修改pom.xml文件,在</dependencies>的前一行添加thymeleaf模板引擎依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
修改后IDEA右下角提示Maven projects need to be imported,选择Enable Auto-Import自动下载更新的依赖。
2.配置aplication.yml
重命名application.properties为application.yml(这样改之后可以让配置更加简洁)
修改aplication.yml为如下内容:
spring:
thymeleaf:
prefix: classpath:/templates/
3.编写HTML文件
在src/main/resources/templates目录下新建一个html文件
输入文件名 index-->OK
编写index.html内容
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>springboot web</title>
</head>
<body>
<h1>Hello Spring Boot!!!</h1>
<p th:text="${hello}"></p>
<div>
<p th:text="${say}"></p>
</div>
</body>
</html>
4.编写控制类
新建一个存放控制类的controller包
新建控制类HTMLController.java
编辑HTMLController.java内容如下:
package com.jipson.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.HashMap;
@Controller
public class HTMLController {
@RequestMapping("/hello")
public String helloHtml(HashMap<String, Object> map, Model model) {
model.addAttribute("say","欢迎欢迎,热烈欢迎");
map.put("hello", "欢迎进入HTML页面");
return "index";
}
}
5.启动项目
右键DemoApplication类-->Run 'DemoApplication'
6.浏览器验证
浏览器输入localhost:8080/hello,看到如下界面为成功:
完整工程代码:
完整代码下载 提取码:fdls
参考:https://www.jianshu.com/p/198497e08e00
完成! enjoy it!