You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot如何为JS、CSS等静态资源设置独立上下文路径?

解决方案

问题根源在于你设置了server.servlet.context-path=/login,导致应用所有默认请求都带上/login前缀,包括静态资源映射。要让/static路径直接在根路径下生效,可按以下两种方式配置:

方式一:利用Spring Boot自动配置(推荐)

  1. 修改application.properties,添加静态资源路径配置:

    server.servlet.context-path=/login
    # 指定静态资源的请求路径(根路径下的/static/**)
    spring.mvc.static-path-pattern=/static/**
    # 指定静态资源的实际存储位置
    spring.web.resources.static-locations=classpath:build/dist/static/
    
  2. 删除自定义的ViewRegistry.java,Spring Boot的自动配置会接管静态资源映射,避免自定义配置与自动配置冲突。

方式二:保留自定义配置并调整DispatcherServlet映射

如果需要保留ViewRegistry.java的自定义配置,可按以下步骤修改:

  1. 修改application.properties,配置DispatcherServlet处理根路径下所有请求:

    server.servlet.context-path=/login
    server.servlet.path=/*
    
  2. 保持ViewRegistry.java不变,确保资源处理器映射规则正确:

    @Configuration
    public class ViewRegistry implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/static/**")
                    .addResourceLocations("classpath:build/dist/static/");
        }
    }
    

验证配置

完成配置后重启应用:

  • 控制器请求依然可通过localhost:8080/login/forgot.do正常访问
  • 静态资源可通过localhost:8080/static/css/style.css正常加载

内容的提问来源于stack exchange,提问作者Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 19:17:28