项目需求
有时需要做一些交互非常少只需要展示的简单页面,如果使用vue3,必须做前端和后端,比较麻烦,如果使用springboot+thymeleaf+jquery,只用写一个工程,不用部署nginx可以快速的得到页面,非常方便。
springboot中有一些设置与常规的后端的设置不一样,记录一下:
1.引入的依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2,添加 controller
@Controller
public class Hello {
@RequestMapping("/hello")
public String get(Model model){
return "index";
}
}
以上代码表示访问/hello,返回index.html 页面
3,添加模板
在resources文件夹下建立/templates文件夹,用于保存模板
4. 在application.yml文件中设置thymeleaf模板地址
spring:
thymeleaf:
prefix: classpath:/templates/
5. 设置静态文件夹地址
在resources文件夹中添加/static/js
并把jquery文件存放于此
如图所示:
在application.yml文件中设置静态文件夹地址
spring:
web:
resources:
static-locations: classpath:/static/
6.在index.html中引入jquery
在html文件的head中添加如下:
<script type="text/javascript" th:src="@{/js/jquery-3.7.1.min.js}" ></script>
在页面中添加
<script>
$(()=>{
alert("loaded!")
})
</script>
刷新页面得到
证明引入jQuery成功!