I need to make an ajax request to server to check if user's session expired. The problem is that this request will continue user session if session was not expired. How to tell Spring not to continue session for this particular request?
Asked
Active
Viewed 250 times
0
-
`request.getSession(false)`. Details described in [HttpServletRequest#getSession(boolean)](https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/HttpServletRequest.html#getSession-boolean-) doc – Feb 19 '19 at 10:57
-
can you share some of your code? – user3454581 Feb 19 '19 at 11:02
-
This has absolutely nothing to do with Spring. You would need to ping the server without the session cookie (is this even possible https://stackoverflow.com/questions/39149482/is-it-possible-to-prevent-cookies-to-be-sent-in-every-http-request) but send the session id as some parameter and then interrogate all sessions using perhaps one of the mechanisms outlined here: https://stackoverflow.com/questions/3771103/how-do-i-get-a-list-of-all-httpsession-objects-in-a-web-application Seems like a lot of work. What is the use case? – Alan Hay Feb 19 '19 at 11:50
-
@AlanHay need to show a notification on client for user that his session was expired – mikach Feb 19 '19 at 13:38
-
It is not entirely clear what you are asking but I am reading it as you want to ping the server but do not want this ping to reset the timeout timer. If so, consider server side push as an alternative to client ping. For example: https://www.baeldung.com/spring-server-sent-events – Alan Hay Feb 19 '19 at 15:34
1 Answers
0
One possible way to expire the HTTP session is to expire the JSESSIONID cookie. You can get an array of cookies from HttpServletRequest's getCookies() method. You can find the cookie with name JSESSIONID from that array. We can not delete the cookie using the Cookie object though. But we can expire it by setting the max age to zero i.e. cookie.setMaxAge(0). Here is a possible implementation you can try to use:
public static void expireJSessionIdCookie(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
Optional<Cookie> cookieOpt = Stream.of(cookies)
.filter(c -> c.getName().equalsIgnoreCase("JSESSIONID"))
.findFirst();
if (cookieOpt.isPresent()) {
Cookie cookie = cookieOpt.get();
cookie.setMaxAge(0);
}
}

Shah Minul Amin
- 86
- 8