访问顺序:Controller->静态资源->404
静态资源默认访问路径
前端访问:http://localhost:8080/page4.html
- classpath:/static
- classpath:/public
- classpath:/resources
- classpath:/META-INF/resources
自定义访问路径
自定义后默认访问路径失效
yml配置文件配置
spring:
# 匹配方式-即前缀
mvc:
static-path-pattern: "/file/**"
# 寻址路径-即从哪个文件夹取
web:
resources:
static-locations: classpath:/resources/
实际访问:http://localhost:8080/file/page3.html
且只能访问page3.html
WebMvcConfigurationSupport配置优先级更高
继承WebMvcConfigurationSupport重写addResourceHandlers方法
package com.xyz.toolserver.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* @date 2023/7/13 11:20
* @description
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//匹配方式
registry.addResourceHandler("/file/**")
.addResourceLocations("classpath:/static/");
}
}
实际访问:http://localhost:8080/file/page1.html
且只能访问page1.html
Controller重定向静态资源
package com.xyz.toolserver.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @date 2023/7/13 11:28
* @description
*/
@RequestMapping("/static")
@RestController
public class StaticController {
@GetMapping("/page")
public void page(HttpServletResponse resp) throws IOException {
resp.sendRedirect("/page1.html");
}
}
http://localhost:8080/static/page
重定向
http://localhost:8080/page1.html
关闭访问静态资源
spring:
web:
resources:
add-mappings: false
标签:web,SpringBoot,静态,springframework,访问,org,import,annotation,资源
From: https://blog.51cto.com/xyz5/7012499