1、安装maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、在resources目录下新建static和templates,文件夹,其中templates文件夹下放html静态页面,目录结构如下:
html测试代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<div>
欢迎来到主页面
</div>
</head>
<body>
<script type="text/javascript" th:src="@{/js/test.js}"></script>
<script type="text/javascript">
let result=initLoad();
alert(result)
</script>
</body>
</html>
test.js测试代码
const initLoad=()=>{
return "测试初始加载函数!";
}
3、配置文件
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
cache: false
4、主启动类
@SpringBootApplication
public class HomeServiceApplication extends WebMvcConfigurationSupport {
public static void main(String[] args) {
SpringApplication.run(HomeServiceApplication.class, args);
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/css/");
registry.addResourceHandler("/js/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/js/");
super.addResourceHandlers(registry);
}
}
5、测试控制器
@Controller
public class HomeController {
@RequestMapping("/")
public String getHomeIndex(){
return "web/home";
}
}
注:要使用@Controller
6、测试接口直接返回html页面了