1、添加依赖
<!-- springboot 视图模板依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、在 src/main/resources/templates 目录下新建视图文件:index.html
...
<h1>测试223322 eee</h1>
<p th:text="${hello}"></p>
...
3、在控制器里加上
// 首页
@RequestMapping("/index")
public String index() {
System.out.println("进来了 - 首页");
return "index.html";
}
4、 浏览器访问:
http://localhost:8081/index.html
5、如果要更改默认文件夹路径,在yml添加配置
spring:
# 页面模板配置
thymeleaf:
prefix: classpath:/html/
# 此时就可以在 src/main/resources/html文件夹下新建 *.html 文件了
6、如果要万能路由:在任意@Controller里加一个
// 万能路由, 匹配所有 html文件 ,
@RequestMapping("/**/*.html")
public String helloHtml(HttpServletRequest request) {
request.setAttribute("hello", "任意值");
return request.getRequestURI();
}
7、特殊路由:
// 特殊路由,此路由因为限定范围小,所以优先权大于万能路由
@RequestMapping("/he.html")
public String he(HttpServletRequest request) {
return "/he.html";
}
8、热更新
java代码热更新:
以调试模式启动,可以做到java代码热更新
html文件热更新方法
借助springboot插件可以做到html热更新,在pom.xml里添加:
<!-- 热更新插件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
此方法有个限制,那就是
只有在编辑器里修改代码才会热更新
在编辑器外修改代码就会失效
解决方案:
eclipse:设置中General中workspace中设置refresh auto...
idea:暂未了解
以上方案仍有5秒左右的延迟,非常不舒服,再寻找解决方案的话,只有借助第三方工具了
例如:gulp、wabpack等等,将文件从源目录复制到编译目录,这是另一套技术,这里暂不赘述
参考文章:https://my.oschina.net/yejunxi/blog/845752
9、注:
万能路由可以用 @RequestMapping("/**") 匹配所有文件,这时候就可以映射 js css 等文件 但不能映射图片文件
想映射图片文件,可以把图片放在static文件夹下,(此时不能@RequestMapping("/**"),因为这样把图片文件也拦了)
说实话,这种模式除了SEO以外,还不如 前后台分离开发模式