SpringBoot 集成 Thymeleaf 教程

项目结构

  • static:静态资源路径,js,css,image 等
  • templates:前端页面
    在这里插入图片描述

加依赖

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

加配置

spring:
  #thymelea模板配置
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    mode: HTML
    encoding: UTF-8
    #热部署文件,页面不产生缓存,及时更新
    #本地开发时候关闭,部署时候开启
    cache: false
    #检查模板位置是否存在。
    check-template-location: true
    #Content-Type值
    servlet:
      content-type: text/html

资源拦截器

PS:解决前端资源 net::ERR_ABORTED 404 问题

/**
 * 资源拦截器
 * @author: linjinp
 * @create: 2020-03-19 17:38
 **/
@Configuration
public class XXXXWebMvcConfigurationSupport extends WebMvcConfigurationSupport {

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/js/");
        registry.addResourceHandler("/style/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/style/");
        registry.addResourceHandler("/images/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/images/");
        // 这么写的话,前端资源路径都应该从 /static 文件夹开始
        // registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/");
        super.addResourceHandlers(registry);
    }
}

注意

  1. 资源引用,前面应该 / 开头:
    在这里插入图片描述在这里插入图片描述
  2. 如果拦截器上配置的是 /static/**,那么资源引用也应从 /static/ 文件夹开始,否则拦截器找不到映射
  3. 配置好后如果发现没生效,先重启 IDEA 尝试,发现 IDEA 有 Bug

页面跳转

PS:注解应该使用 @Controller,如果使用 @RestController 会发现一直返回字符串

@Controller
@RequestMapping(value = "/app/auth")
public class AppAuthController {

    @RequestMapping(value = "/appAuth")
    public String appAuth(@RequestParam String code, Model model) {
        model.addAttribute("code", code);
        return "app-auth";
    }
}

效果图

在这里插入图片描述

发布了107 篇原创文章 · 获赞 414 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/qq_37143673/article/details/104983947