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

如何在Java Spring MVC中将Cookie的Path属性设置为应用的实际虚拟目录路径

Hey there! I get that you want to set the cookie path to your Spring MVC app's actual context path instead of the fixed / in your web.xml config. Let's break down how to solve this since static web.xml can't dynamically grab the context path for you.

If you're using Spring MVC (especially with Spring Session), you can create a configuration bean to dynamically set the cookie path based on your app's context path:

import org.springframework.session.web.http.DefaultCookieSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.ServletContext;

@Configuration
public class CookieConfig {

    private final ServletContext servletContext;

    // Inject ServletContext to get the dynamic context path
    public CookieConfig(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    @Bean
    public DefaultCookieSerializer cookieSerializer() {
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        // Set cookie path to the app's actual context path
        serializer.setCookiePath(servletContext.getContextPath());
        // Match your original session timeout (40 minutes = 40*60 seconds)
        serializer.setCookieMaxAge(40 * 60);
        return serializer;
    }
}

This bean will override the <cookie-config> settings in your web.xml, so you can remove that section if you want—no more hardcoded / path!

Solution 2: Custom Filter for Non-Spring Session Projects

If you aren't using Spring Session, you can create a Servlet Filter to adjust the session cookie's path after each request:

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "CookiePathFilter", urlPatterns = "/*")
public class CookiePathFilter implements Filter {

    private String appContextPath;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Grab the context path once during filter initialization
        appContextPath = filterConfig.getServletContext().getContextPath();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // Let the request process first
        chain.doFilter(req, res);

        // Update the JSESSIONID cookie's path to the app's context path
        Cookie[] cookies = res.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("JSESSIONID".equals(cookie.getName())) {
                    cookie.setPath(appContextPath);
                    res.addCookie(cookie);
                    break;
                }
            }
        }
    }

    @Override
    public void destroy() {
        // Cleanup if needed
    }
}

Make sure your project supports Servlet 3.0+ annotations (so @WebFilter works), or register the filter manually in your web.xml.

Bonus: Spring Boot Quick Fix

If you're on Spring Boot, it's even simpler—just add these lines to your application.properties (or application.yml):

# Set cookie path to match the app's context path
server.servlet.session.cookie.path=${server.servlet.context-path}
# Set session timeout to 40 minutes
server.servlet.session.timeout=40m

That's it! No code required, and it dynamically uses your app's deployed context path.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 16:07:35