0
点赞
收藏
分享

微信扫一扫

SpringBoot静态资源

访问顺序:Controller->静态资源->404

静态资源默认访问路径

前端访问:http://localhost:8080/page4.html

SpringBoot静态资源_html

  1. classpath:/static
  2. classpath:/public
  3. classpath:/resources
  4. 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

举报

相关推荐

0 条评论