• SpringBoot 返回thymeleaf页面报错


    org.thymeleaf.exceptions.TemplateInputException: Error resolving template [index], template might not exist or might not be accessible by any of the configured Template Resolvers

    我的代码:

    package com.example.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    @RequestMapping("/demo")
    public class IndexController {
    
        @GetMapping(value = "index")
        public String showIndex(Model model) {
            model.addAttribute("h1_text", "this is a index page!");
            return "index";
        }
    }

    解决办法,返回路径前加上 / :

    package com.example.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    @RequestMapping("/demo")
    public class IndexController {
    
        @GetMapping(value = "index")
        public String showIndex(Model model) {
            model.addAttribute("h1_text", "this is a index page!");
            return "/index";
        }
    }

    遇到类似问题可以加上或去掉 / 试下。

    其他注意问题:

    1、在入口Application不要忘记加入你的包 

    @SpringBootApplication(scanBasePackages = {"com.example.controller"})

    2、@Controller 、@RestController、@ResponseBody 三者使用注意你是返回页面、字符串还是JSON数据

    3、使用thymeleaf作为模板文件,要求HTML格式必须为严格的html5格式,必须有结束标签,否则会报错,将其改为非严格的即可:LEGACYHTML5

    application.properties

    #是否开启缓存,开发时可设置为false,默认为true
    spring.thymeleaf.cache=false
    #检查模板是否存在,默认为true
    spring.thymeleaf.check-template=true
    #检查模板位置是否存在,默认为true
    spring.thymeleaf.check-template-location=true
    #模板文件编码,UTF-8
    spring.thymeleaf.encoding=UTF-8
    #模板文件位置
    spring.thymeleaf.prefix=classpath:/templates
    #Content-Type配置
    spring.thymeleaf.servlet.content-type=text/html
    #模板文件后缀
    spring.thymeleaf.suffix=.html
    #启用MVC Thymeleaf视图分辨率
    spring.thymeleaf.enabled=true
    #模板编码
    spring.thymeleaf.mode=LEGACYHTML5
    #应该中解决方案中排除的视图名称的逗号分隔列表
    spring.thymeleaf.excluded-view-names=

    application.yml

    spring.thymeleaf.content-type: text/html 
    spring.thymeleaf.cache: false 
    spring.thymeleaf.mode: LEGACYHTML5

    pom.xml中加入

    1 <dependency>
    2             <groupId>net.sourceforge.nekohtml</groupId>
    3             <artifactId>nekohtml</artifactId>
    4             <version>1.9.22</version>
    5         </dependency>
  • 相关阅读:
    jstack 分析程序性能
    网关-zuul介绍 第一篇 网关解决的问题
    通过Fegin远程调用 ,返回JPA Page 对象报错
    css自定义字体
    CSS3选择器
    表格操作
    商品筛选条件
    多级菜单
    一排元素往下掉
    控制提示框不溢出父级盒子
  • 原文地址:https://www.cnblogs.com/mingforyou/p/14610103.html
Copyright © 2020-2023  润新知