当我们spring-boot项目的前端资源文件没有放在static文件夹下的话,就会造成404
以下解决方法可以不通过Controller直接静态页面访问(使用SpringMVC方法实现)
开始操作
引入依赖 (这边使用的spring-boot是2.6.13版本)
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.6.13</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
然后在resources文件夹内创建hello文件夹,我们再在这个文件夹内创建一个名为index.html(我这边随便起名的)页面
<html>
<body>
<h1>hello word!!!</h1>
<p>this is a html page</p>
</body>
</html>
然后我们可以先启动Spring-Boot项目来访问一下这个静态页面地址http://localhost:8080/hello/index
可以发现是404的状态
然后我们创建一个config类,进行继承WebMvcConfigurationSupport类
config方法
@Configuration
public class MvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//资源映射 访问/hello/**的页面去映射到本地资源resources的/hello的文件夹内
registry.addResourceHandler("/hello/**")
.addResourceLocations("classpath:/hello/");
}
}
我们接着再重启一下项目重新进行访问这个地址,就可以发现可以正常访问了