After invalidation of a session, is it possible to get new session through request object via request.getSession() without making a new request?
My request object flow to 1st page to 2nd page and 2nd page to 1st page again 1st page to 2nd page and again same 2nd page to 2nd page ....request page can not be change but every time request 1st page to 2nd page we need to fetch detail to session and invalidate it and again created it.. like this
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);
but this not work on 2nd time it gives to null session or details
also try to set session id in coming cookies like this
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());
}
}
As-per the Javadocs, just call request.getSession()
:
Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.
So calling the getSession
method will create you a new session:
final HttpSession session = request.getSession()
Here's an example JSP that proves the code works:
test.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>
test2.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>
When executed on Tomcat6, the output in my browser is:
Session is org.apache.catalina.session.StandardSessionFacade@9317bfb
Test 2
which indicates test.jsp
was exectued and successfully forwarded to test2.jsp.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With