SpringBoot静态资源
  zEbHO6cVnp49 2023年11月02日 32 0

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

静态资源默认访问路径

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

SpringBoot静态资源_静态资源

  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
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  X5zJxoD00Cah   2023年11月19日   35   0   0 管理系统githtml
  X5zJxoD00Cah   2023年11月26日   45   0   0 Pythonhtml
  zhRhucGD3dLm   2023年11月22日   38   0   0 属性选择器选择器html
  X5zJxoD00Cah   2023年11月13日   36   0   0 HTML5html
zEbHO6cVnp49