Java Spring Session not persist between requests

Kun*_*Lun 0 java session spring

I have this controller

@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");

    }

}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

PS:我的应用程序以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());

    }

}
Run Code Online (Sandbox Code Playgroud)

在每次请求时/sess都会打印另一个ID。

Kun*_*Lun 5

真正的问题出在JSessionID路径上。

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

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

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

ProxyPassReverseCookiePath /myapp /
Run Code Online (Sandbox Code Playgroud)

这是我的最终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 /emrahub-1.0.0 /

</VirtualHost>
Run Code Online (Sandbox Code Playgroud)