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

Spring MVC首次加载资源时spring:url追加jsessionid导致资源无法加载

解决Spring MVC首次加载资源带jsessionid的问题

原因分析

首次访问站点时,浏览器尚未存储JSESSIONID Cookie,Spring MVC会自动启用URL重写,将jsessionid追加到URL后维持会话。但静态资源(JS/CSS)不需要会话跟踪,且资源处理器无法正确解析带;jsessionid后缀的路径,导致资源加载失败。刷新后浏览器已存储Cookie,URL重写不再触发,资源即可正常加载。

解决方案

1. 修改资源处理器,移除URL中的jsessionid后缀

调整Spring MVC资源配置,在资源解析时主动截断;jsessionid部分:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("resources/**")
            .addResourceLocations("/resources/")
            .resourceChain(true)
            .addResolver(new PathResourceResolver() {
                @Override
                protected Resource getResource(String resourcePath, Resource location) throws IOException {
                    // 拆分URL,只保留jsessionid前的部分
                    resourcePath = resourcePath.split(";")[0];
                    return super.getResource(resourcePath, location);
                }
            });
}

2. 用过滤器禁用静态资源的URL重写

在web.xml中添加过滤器,拦截静态资源请求并禁用URL重写:

<filter>
    <filter-name>staticResourceNoRewriteFilter</filter-name>
    <filter-class>org.springframework.web.filter.OncePerRequestFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>staticResourceNoRewriteFilter</filter-name>
    <url-pattern>/resources/*</url-pattern>
</filter-mapping>

实现过滤器逻辑:

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // 直接设置会话Cookie,避免URL重写
    String sessionId = request.getSession().getId();
    response.setHeader("Set-Cookie", String.format("JSESSIONID=%s; Path=/; HttpOnly; SameSite=Lax", sessionId));
    filterChain.doFilter(request, response);
}

3. 调整spring:url的使用方式

确保路径为绝对路径(开头加/),并关闭HTML转义,避免触发URL重写:

<spring:url value="/resources/core/js/starter.js" var="starterJs" htmlEscape="false"/>
<script src="${starterJs}" type="module"></script>

4. Tomcat容器级配置移除jsessionid

如果使用Tomcat,在context.xml中添加重写规则,自动剥离静态资源URL中的jsessionid:

<Context>
    <Valve className="org.apache.catalina.valves.rewrite.RewriteValve">
        <Property name="rewriteCond">%{REQUEST_URI} ^/resources/.*$</Property>
        <Property name="rewriteRule">^(.*);jsessionid=.*$ $1</Property>
    </Valve>
</Context>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 06:45:29