How can JavaScript be made aware that an HTTP session (user login) has started?

108 Views Asked by At

I am making an e-commerce website and Im having trouble identifying that a user is actively logged in so that a cart purchase can be made directly under that user.

Using Java inside the Eclipse IDE, "HttpSession session = request.getSession();" is how the session is initiated. Im not sure how to confirm that it has actually been started. I have tried functions to get the session attribute in JavaScript (if session has started) and if successful the log in button should change to log out but each time it is run there is no difference. I seek to pull the login email from the session attribute so that I can make a purchase in JavaScript and send it back to the Java Servlet.

Java Servlet:

//begin session
HttpSession session = request.getSession();

//session storage attributes
session.setAttribute("loggedInUser", true);
session.setAttribute("user", email);
session.setAttribute("price", price);
session.setAttribute("points", points);
session.setAttribute("item", item);

JavaScript:

//If user is logged in 
function checkLoggedIn()
{
if (sessionStorage.getItem('loggedInUser') === 'true') 
{
      // User is logged in, change sign-in link to log-out link
      document.getElementById('signin-link').textContent = 'Log Out';
}
else
{
      document.getElementById('signin-link').textContent = 'Sign In';
}

}
1

There are 1 best solutions below

2
John Williams On

You really should be using something like Thymeleaf or JSP to simplify this.

It is possible with pure Servlet as follows:

Modify the servlet response for the login call in Java to return a value that indicates if the session was logged on correctly. Something like this:

Use a 200 on this call for successful login and 400 for a failure.

response.setStatus(400); // for failure

Use this response to populate the session storage:

sessionStorage.setItem('loggedInUser', 'true')

To achieve this with Servlet/JSP use your Servlet as is. In the JSP set the value in JavaScript with embedded Java <%=%> as follows:

sessionStorage.setItem('loggedInUser', '<%=session.getAttribute(“loggedInUser”)%>')