'How to access session data across servlets in java?

I am working on an application with react on the front end and java(running on tomcat server JDK17) in the backend. Whenever I login into the application, I send the user data to the server(java) and see if the user exists in the database. Whenever I move across the components in the react application, I would like to check if the user is authenticated/allowed to use that particular component. Hence I stored the data onto a session in the login servlet. I tried to access the session from another servlet called AuthenticationServlet, it returns null. Do I have to configure something so that I can access the data across all the servlets.

This is how I set the session data in the login servlet:

HttpSession session = request.getSession();
session.setAttribute("uname", uname);

Printing it on the console in the same servlet displays the username. This is where I'm accessing it(AuthenticationServlet)

HttpSession session = request.getSession();
String k = (String) session.getAttribute("uname");
System.out.println(k);

This displays null. What am I doing wrong or did I miss something. Much appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source