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类型的,最后还是不能跳页面。比如:

错误形式
~~@RestController~~ 
@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

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值