-1

Suppose I have a servlet that processes logins. When the login is successful the user will create a session for this user. Then redirects to a homepage.

Let's say the homepage has a link "view all". This link calls a servlet, viewall.html to process all the data from the database then redirect to a jsp page (viewall.jsp) that will display the data from the servlet.

Somewhere from the servlet viewall.html to the jsp viewall.jsp, I would like to have code that looks like this:

if (session attribute user is null) {
    // redirect to the login page
} else {
    // if in the servlet, retrieve the data from the database
    // if in the jsp, display the data
}

What is the better way to check if there is a session, on the servlet or the jsp? Note I know about filters, let's say the project can't use filters.

lightning_missile
  • 2,821
  • 5
  • 30
  • 58

3 Answers3

2

It is the same using a servlet of a filter. The general way is :

  • in the servlet that processes login you

    • create a new session

      Session old = request.getSession(false); // first invalidate old if it exists
      if (old != null) {
          session.invalidate();
      }
      Session session = request.getSession(true); // next create one
      
    • put the user id as attribute of the session

      session.setAttribute("USERID", userId);
      
  • then in the element (filter of servlet) where you want to know whether you have a registered user :

    Session = request.getSession(false);
    if ((session == null) or (session.getAttribute("USERID") == null)) {
        response.sendRedirect(homeUrl);
        return; // no need to process further (if in a filter no need to go down the chain)
    }
    
  • in the servlet after controlling you have a logged on user, forward to the jsp

    request.getRequestDispacher("/path/to/displayer.jsp").forward(request, response);

That's all ...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

If you want to check this before creating, then do so:

HttpSession session = request.getSession(false);
 if (session == null) {
  // Not created .
  session = request.getSession();
  } else {
// Already created.
  }

If you don't care about checking this after creating, then you can also do so:

HttpSession session = request.getSession();
 if (session.isNew()) {
  // newly  created.
 } else {
// Already created.
  }
Anand Dwivedi
  • 1,452
  • 13
  • 23
0
<% if(session.getAttribute("sessionname")==null)

{
response.sendRedirect("index.jsp");
else
{
String activeUser=session.getAttribute("sessionname").toString();
}

I hope it helps you

Birhan Nega
  • 663
  • 12
  • 24