使用IDEA构建spring boot项目访问报错404或500

175 阅读1分钟

前提

version:spring boot 2.6

项目结构

image.png

HelloController.java

package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

    @RequestMapping("/index")
    public String sayHello(){
        return "index";
    }
}

运行结果

image.png

解决方案

thymeleaf

pom.xml添加thymeleaf依赖

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

static-path-pattern

application.yml设置静态资源地址

spring:
  mvc:
    static-path-pattern: /templates/**

玄学

springboot已经配置了static-path-pattern的默认地址,但是并没能生效。在配置static-path-pattern后,删除该配置,仍然能正常访问项目。