springboot整合thymeleaf跳转html页面
最近在做项目的过程中需要在springboot中跳转html页面,参考网上的帖子最后总算是实现了,但是发现在整合的过程中存在很多易犯错误,特此记录一下。
1.pom中引入thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.添加thymeleaf配置
有两种方式:一种时在application.properties文件中配置,一种是在application.yaml配置文件中配置。
spring:
# thymeleaf页面模板配置
thymeleaf:
prefix: classpath:/templates/
suffix: .html
prefix配置的是视图模板的位置,我试着不放在templates下面发现总是报错,不知道是否可以通过其他配置改成别的路径。
易犯错误配置
spring:
mvc:
view:
suffix: .ftl
prefix: classpath:/templates/
因为使用了thymeleaf所以,使用mvc的自然是无用的,必须要修改为thymeleaf才行
3.html模板
作为thymeleaf模板的html页面中的元素标签必须是闭合的,否则会报错。比如
<meta charset="utf-8">
<base href="/">
<title>thymeleaf</title>
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"></meta>
<link rel="stylesheet" href="/css/swiper.min.css">
其中“meta、base、link标签就没有闭合,启动时候就会报错。
需要在html标签中加入xmlns:th=“http://www.thymeleaf.org”
<html id="ng-app" ng-app="app"
xmlns:th="http://www.thymeleaf.org">
4.controller注解
我刚开始配置的时候,按照例子写方法怎么都不能跳页面,后来发现是controller层中的注解是@Restcontroller而不是@Controller,这样导致及时在方法上返回的是string类型的,最后还是不能跳页面。比如:
错误形式
[email protected]~~
@RequestMapping("user")
public class UserController {
@RequestMapping("toIndex")
public String toIndex(){
return "idx/index";
}
}
@RestController注解相当于@Controller注解和@ResponseBody注解,所有不会跳转页面,需要改成下面的形式。
@Controller
@RequestMapping("user")
public class UserController {
@RequestMapping("toIndex")
public String toIndex(){
return "idx/index";
}
}
5.总结
目前测试通过上面的配置就可以正常的跳转到html页面了,终于不用再使用jsp页面了。
参考资料
https://blog.csdn.net/sicily_winner/article/details/78985187
https://blog.csdn.net/qq_16307345/article/details/78038224?locationNum=10&fps=1
上一篇: java 手机号的正则校验