【问题标题】:Java Spring Session not persist between requestsJava Spring Session 在请求之间不会持续存在
【发布时间】:2021-01-10 00:45:05
【问题描述】:

我有这个控制器

@Controller
@RequestMapping(value = "/login")
public class Login{

    @RequestMapping
    public ModelAndView mainPage(HttpServletRequest request){

        request.getSession().setAttribute("testSession", "Session test");

        return new ModelAndView("/login");

    }

    @RequestMapping(value = "/check")
    public View check(HttpServletRequest request){

        System.out.println(request.getSession(false)); //null

        return new RedirectView("/login");

    }

}

当访问/login 时,我创建一个会话并在其中添加一个属性"testSession"request.getSession().setAttribute("testSession", "Session test");

在页面/login 上有这个<form action="/login/check" method="post">

/login/check 上,我尝试在/login 上创建会话,但它为空。

为什么会话在请求之间不存在?

P.S.:我的应用在远程服务器上运行,Tomcat 和 Apache 作为反向代理,我通过 https://mydom.com 访问我的应用

更新

我创建了一个控制器来测试会话:

@Controller
@RequestMapping(value = "/sess")
public class TestSession{

    @RequestMapping(method = RequestMethod.GET)
    public void mainPage(HttpServletRequest request, HttpServletResponse response) throws IOException{

        //get or create session
        HttpSession session = request.getSession();

        response.setContentType("text/html");
        response.getWriter().println(session.getId());

    }

}

/sess 的每个请求都会打印另一个ID。

【问题讨论】:

  • 你如何测试这个?确保将会话 ID 从客户端发送回服务器。
  • @M.Deinum 究竟如何?我是 spring/web 的新手
  • 这与 Spring 无关,而与您如何测试它有关。如果您没有发送 sessionId cookie(假设您正在使用 cookie),那么就没有什么可以恢复的了。还要确保你已经正确配置了 Spring Session。
  • @M.Deinum 我们可以在这里谈谈chat.stackoverflow.com/rooms/195135/… 吗?我觉得我缺少信息。
  • 只需解释(或展示)您是如何测试它的。您正在讨论页面,哪些页面显示您是如何做事的。还要添加你的 Spring Session 配置(应该配置一个过滤器)。

标签: java spring session


【解决方案1】:

真正的问题在于 JSessionID 路径。

JSessionID 的路径是/myapp。那是Tomcat的结果,因为我的应用程序通常在mydom.com:8080/myapp下运行

但是使用 Apache 作为反向代理,我直接从 mydom.com/ 运行我的应用程序,这使得 JSessionID 无效,因为我不在 mydom.com/myapp 上。

所以我在 Apache 的虚拟主机中添加了一个新行(其中设置了反向代理)来更改 cookie 的路径:

ProxyPassReverseCookiePath /myapp /

这是我最后的VirtualHost,现在会话在请求之间持续存在。

<VirtualHost *:80>

    ServerName mydom.com

    ProxyRequests Off
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:8080/myapp/
    ProxyPassReverse / http://127.0.0.1:8080/myapp/
    ProxyPassReverseCookiePath /myapp /

</VirtualHost>

【讨论】:

  • 如果有人认为此答案中缺少/错误信息,请留下评论以更新回复。
【解决方案2】:

您使用的是 Spring Security 吗?也许你可以设置 http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER) 如果您自己管理会话

参考:https://www.baeldung.com/spring-security-session

【讨论】:

  • 我没有使用 spring security
  • 这只影响 Spring Security 处理会话的方式,而不影响应用程序其余部分的处理方式。
猜你喜欢
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
  • 2014-08-26
  • 2014-02-12
  • 2019-04-19
  • 2014-08-28
  • 1970-01-01
  • 2012-04-17
相关资源
最近更新 更多