Issue
I want to get Java HttpSession
by JSESSIONID. Is it possible? If yes, how?
Solution
You'll basically need to manually collect them all in a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Map.html" rel="nofollow noreferrer">Map
using a HttpSessionListener
yourself.
@WebListener
public class HttpSessionCollector implements HttpSessionListener {
private static final Map<String, HttpSession> SESSIONS = new ConcurrentHashMap<>();
@Override
public void sessionCreated(HttpSessionEvent event) {
HttpSession session = event.getSession();
SESSIONS.put(session.getId(), session);
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
SESSIONS.remove(event.getSession().getId());
}
public static HttpSession find(String sessionId) {
return SESSIONS.get(sessionId);
}
}
Then, anywhere you want just do HttpSessionCollector.find(sessionId)
to get the HttpSession
in question.
That said, this is a huge smell. There are certainly better ways to solve the actual functional requirement than this ;) As I commented in your follow-up question:
This is the 2nd time that you asked a question which in real world should never be practiced. Honestly said, this all smells. What is it, the problem for which you think that getting the
HttpSession
associated with JSESSONID in server side and getting the JSESSIONID value in client side is "the" solution? Elaborate about this in a new question, you'll get answers how to do it the right way.
Take it serious. We're not teasing you, we're just trying to help you in the right direction to avoid that your project/webapp will break due to security holes and bad practices and/or that you will get fired.
Answered By - BalusC
Answer Checked By - David Marino (JavaFixing Volunteer)