在invalidate()之后,是否可以从请求对象获取新会话?

Mas*_*323 5 session servlets invalidation

会话无效后,是否可以通过request.getSession()通过请求对象获得新会话而无需发出新请求?

我的请求对象流到第一页到第二页,第二页又到第一页,第一页到第二页,再到第二页到第二页....请求页不能更改,但是每次请求第一页到第二页时我们需要获取详细信息进行会话并使它无效,然后再次创建它。

HttpSession session = request.getsession(false)
String user = (String)session.getAttribute("name");
session.invalidate();
session=request.getSession(true);
RequestDispacher dis = request.requestDispatcher("path");
dis.forword(request,respone);
Run Code Online (Sandbox Code Playgroud)

但这在第二次上不起作用,它提供了空会话或详细信息

也尝试像这样在即将到来的cookie中设置会话ID

Cookie[] c = request.getCookies();
            for(Cookie k: c){
                if(k.getName().equalsIgnoreCase("JSESSIONID")){
                    System.out.println("k.getValue() : "+k.getValue());
                    System.out.println("httpSession.getId() : "+httpSession.getId());
                    k.setValue(httpSession.getId());
                }
            }
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 5

根据Javadocs,只需调用request.getSession()

返回与此请求关联的当前 HttpSession,或者,如果没有当前会话并且 create 为 true,则返回一个新会话。

如果 create 为 false 并且请求没有有效的 HttpSession,则此方法返回 null。

为了确保会话得到正确维护,您必须在提交响应之前调用此方法。如果容器使用 cookie 来维护会话完整性,并且在提交响应时被要求创建新会话,则会抛出 IllegalStateException。

因此调用该getSession方法将为您创建一个新会话:

final HttpSession session = request.getSession()
Run Code Online (Sandbox Code Playgroud)

下面是一个 JSP 示例,证明代码有效:

测试.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Session invalidation test</title>
</head>
<body>
<% 

// Uses implicit session for JSP

out.println("Session is " + session);
session.invalidate();
out.println("\nNew session is " + request.getSession());

request.getRequestDispatcher("/test2.jsp").forward(request, response);

%>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

测试2.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Session invalidation test</title>
</head>
<body>
<% 

out.println("Session is " + request.getSession());

%>
<h1>Test 2</h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在Tomcat6上执行时,我的浏览器中的输出是:

Session is org.apache.catalina.session.StandardSessionFacade@9317bfb
Test 2
Run Code Online (Sandbox Code Playgroud)

这表明test.jsp已执行并成功转发到 test2.jsp。