温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Springboot中如何使用thymeleaf

发布时间:2021-07-30 17:27:51 来源:亿速云 阅读:391 作者:Leah 栏目:云计算

本篇文章给大家分享的是有关Springboot中如何使用thymeleaf,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

目录结构如下:

Springboot中如何使用thymeleaf

我的预期是访问"/query"路径应该是跳转到hello.html

hello.html代码如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
Hello World!
<div th:text="${msg}">嘿嘿嘿</div>
</body>
</html>

控制器代码如下:

@RestController
public class TAdminController {
    /**
     * 服务对象
     */
    @Resource
    private TAdminService tAdminService;

    @RequestMapping("/query")
    public String query(Model model){
        model.addAttribute("msg","啦啦啦");
        return "hello";
    }

}

错误一:视图解析器跳转直接打印出来

Springboot中如何使用thymeleaf

访问路径之后直接就打印出来了,这与预期不符,于是我在application.yml文件中加入了如下配置

spring:
  thymeleaf:
    cache: false
    prefix: classpath:/static/
    suffix: .html
    encoding: UTF-8

但是效果还是一样的,仔细检查发现是注解用错了

Springboot中如何使用thymeleaf

应该改为@Controller

为什么换了controller注解就好了呢?

@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
意思是:
@RestController注解相当于@ResponseBody + @Controller合在一起的作用。

1)如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。

例如:本来应该到hello.html页面的,则其显示login.

2)如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。

3)如果需要返回json或者xml或者自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解

@ResponseBody:
作用:

该注解用于将Controller方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后(如:json格式),写入到Response对象的body数据区。

使用时机:

返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用

当我们不需要讲数据封装,而是需要实现页面的跳转的时候,就将@responseBody去掉,然后最后返回跳转的页面名称就好.

错误二:404错误

修改后发现还是报404的错误

Springboot中如何使用thymeleaf

 此时我们thymeleaf模板路径也设置了,后缀也设置了,为什么还是报错了呢,回到控制器发现

Springboot中如何使用thymeleaf

 提示Cannot resolve MVC View 'hello' ,找不到视图hello,那么说明我们的thymeleaf配置没起到作用,回到pom文件看看发现thymeleaf依赖好像不对, 我是直接在创建项目的时候勾选了thyme leaf的,他的thymeleaf依赖如下:

Springboot中如何使用thymeleaf

去maven仓库找到Spring Boot Starter Thymeleaf依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.4.0</version>
</dependency>

 要用Spring Boot Starter Thymeleaf才行,那个那个单纯的thymeleaf不能用,跟mybatis与mybatis-spring整合包的区别差不多。

更换新的依赖后点击右上角的Load Maven Changes

Springboot中如何使用thymeleaf

 注:这里的版本号可以不用写,Spring Boot有版本仲裁中心,以后我们导入依赖默认是不需要写版本;(没有在dependencies里面管理的依赖自然需要声明版本号)

以上就是Springboot中如何使用thymeleaf,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI