今天用idea新建 springboot+thymeleaf 项目
pom引入thymeleaf ,jquery
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</version>
</dependency>
yml文件
server:
port: 8078
servlet:
jsp:
init-parameters:
development: true
spring:
thymeleaf:
cache: false
mode: LEGACYHTML5
prefix: classpath:/templates/
suffix: .html
encoding: UTF-8
template-resolver-order: 2
login.html页面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1"></meta>
<title>首页</title>
<!-- <script type="text/javascript" src="../jquery/jquery-3.7.1.min.js"></script>-->
<script src="https://unpkg.com/jquery@3.5.1/dist/jquery.min.js"></script>
</head>
<body >
<h1>lanren312</h1>
</body>
<script type="text/javascript">
</script>
<script th:inline="javascript"> // 如果用到th取值,这里就必须这么写
$(function () {
var treeList = [[${treeList}]];
});
</script>
</html>
控制层代码
@Controller
public class TestController {
@RequestMapping("/")
public String toLogin() {
return "/login";
}
}
启动项目后在浏览器输入: ip:port ,就能看到 login.html 页面的内容。
接下来打jar包发布,放到服务器上启动运行,一切正常,但是在浏览器访问的时候报错:
Error resolving template [/login], template might not exist or might not be accessible by...
后来查询,控制层return里面的 “/” 去掉
@RequestMapping("/")
public String toLogin() {
return "login";
}
引入jquery参考:
1、可以自己下载一个放到 static目录下 /jquery/jquery-3.7.1.min.js。后面有用到。
<script type="text/javascript" src="../jquery/jquery-3.7.1.min.js"></script>
2、(推荐)可以通过 unpkg 提供的链接来引用它,就无需下载。
<script src="https://unpkg.com/jquery@3.5.1/dist/jquery.min.js"></script>
后续,如果放到服务器上,配合nginx
192.168.1.1:8078/login、192.168.1.1:8078/login2
@RequestMapping("/login")
public String toLogin() {
return "login";
}
@RequestMapping("/login2")
public String toLogin2() {
return "login2";
}
配置nginx反向代理
访问地址: 域名/aa/login、域名/aa/login2
location /aa/ {
proxy_pass http://服务器ip:8078/;
}
访问地址: 域名/bb、域名/cc (不推荐,上面那种简单灵活)
location /bb/ {
proxy_pass http://服务器ip:8078/login/;
}
location /cc/ {
proxy_pass http://服务器ip:8078/login2/;
}
ps: 如果用了js,需要将 /jquery/jquery-3.7.1.min.js 放到nginx配置的目录下。