修改了一下开源项目的目录结构访问突然报错Error resolving template “XXX”
可能原因有如下三种:
第一种可能:
原因:在使用springboot的过程中,如果使用thymeleaf作为模板文件,则要求HTML格式必须为严格的html5格式,必须有结束标签,否则会报错。
在application.yml中添加以下配置
spring: thymeleaf: prefix: classpath:/templates/ mode: HTML cache: false encoding: UTF-8 # 新版本不支持content-type: text/html,故新写法 servlet: content-type: text/html
再在pom.xml 添加以下依赖
<dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency>
第二种可能
原因:Spring Boot没有解析出静态资源文件位置
<build> <!-- 配置将哪些资源文件(静态文件/模板文件/mapper文件)加载到tomcat输出目录里 --> <resources> <resource> <directory>src/main/java</directory><!--java文件的路径--> <includes> <include>**/*.*</include> </includes> <!-- <filtering>false</filtering>--> </resource> <resource> <directory>src/main/resources</directory><!--资源文件的路径--> <includes> <include>**/*.*</include> </includes> <!-- <filtering>false</filtering>--> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
第三种可能原因:可能是由于找不到前端VIew路径的原因。
@GetMapping("/admin") public String admin() { //model.addAttribute("menuTree", permissionService.selectMenuTreeByUserId(((User) SecurityUtils.getSubject().getPrincipal()).getUserId())); return UtilsConst.ADMIN_PREFIX +"index/login"; }
注意:在controller上加注解@Controller 和@RestController都可以在前端调通接口,但是二者的区别在于,当用前者的时候在方法上必须添加注解@ResponseBody,如果不添加@ResponseBody,就会报上面错误,因为当使用@Controller 注解时,spring默认方法返回的是view对象(页面)。而加上@ResponseBody,则方法返回的就是具体对象了。