Link to home
Start Free TrialLog in
Avatar of steven_fl
steven_fl

asked on

Problem in JSP sessions

I am having a problem with sessions.
Even after the user logs out and logs in with a different name, the login screen shows the name of the previous user. When the user logs in after checking the user name and password I do the following.
<%
      session=request.getSession(true);
      session.setAttribute("user",user);
    %>
Then on every other page I write the following code to check for session.

<% if(request.isRequestedSessionIdValid() )
      {
          my code
     }
   else
   { %>
         Not a valid Session
<%  }  %>

In logout I am using the following code

<%  session.invalidate();  %>

Why is this problem?
Secondly I want to know whether this methos of maintaining sessions is the right one or not and if it's not hte right one what's a right way to do it.
Plz help
Avatar of sudhakar_koundinya
sudhakar_koundinya

in checklogin page

<%
String user=(String)session.getAttribute( "user");  
if(user!=null)
    session.removeAttribute("user");
session.setAttribute("user","username");

%>



in logoutpage

<%
   session.removeAttribute("user");// though it is not necessary
   session.invalidate();
%>

 simple logic  and other checkings like isValidSession and bla bla bla are not required
<%
// in all other JSP pages
if(session.isNew())
{
 response.sendRedirect("loginpage");
// or any other code
}
else
{
//your code

sessio.setMaxInactiveInterval(15); // for example here session validates for 15 minuites only
}
%>
Avatar of steven_fl

ASKER

This has still not solved my problem.
The code for loginSubmit.jsp is:

<html>
<head><title>Login Submit</title></head>
<%String userName=request.getParameter("userName");%>
<%String password=request.getParameter("password");%>
<jsp:useBean id="loginSubmitBeanId" scope="page" class="approval.LoginSubmitBean" />

<jsp:setProperty name="loginSubmitBeanId" property="*" />
<body bgcolor="#ffffff">
<%!
   String user;
   String dept;
   String pwd;
   String grade;
%>

<%
    user=(String)session.getAttribute("user");  
    if(user!=null)
    {
             session.removeAttribute("user");
    }
    dept=(String)session.getAttribute("dept");  
    if(dept!=null)
    {
             session.removeAttribute("dept");
    }
      grade=(String)session.getAttribute("grade");  
    if(grade!=null)
    {
             session.removeAttribute("grade");
    }
   int val=loginSubmitBeanId.authenticate();
   if(val==1)
    {
      user=loginSubmitBeanId.u;
      pwd=loginSubmitBeanId.p;
      dept=loginSubmitBeanId.dept;
      grade=loginSubmitBeanId.grade;

      session=request.getSession(true);
      session.setAttribute("user",user);
   //   session.setAttribute("pwd",pwd);
      session.setAttribute("dept",dept);
      session.setAttribute("grade",grade);
  //    response.sendRedirect("localRequest.jsp");
    if(grade.equals("3") || grade.equals("1"))
            {
               response.sendRedirect("menu.jsp");
            }
     if(grade.equals("2"))
            {
               response.sendRedirect("adminMenu.jsp");
            }
 
  }
  else
  {
    response.sendRedirect("loginFailed.jsp");
  } %>

</body>
</html>

The code for LoginSubmitBean.java is

package approval;
import java.sql.*;

public class LoginSubmitBean
{
  String userName,password;
  public String u,p,dept,grade;
  Connection con=null;
  Statement stmt=null;
  ResultSet rs=null;
  //Access sample property
  public String getUserName()
  {
    return userName;
  }
  public void setUserName(String userName)
  {
       this.userName = userName;
  }
  public String getPassword()
   {
     return password;
   }
   public void setPassword(String password)
   {
        this.password = password;
   }
  public int authenticate()
  {
     try
     {
      p=" ";
      u=" ";
      dept=" ";
      grade=" ";

      Class.forName("org.gjt.mm.mysql.Driver");
      con=DriverManager.getConnection("jdbc:mysql://localhost/a");
      stmt=con.createStatement();
      rs=stmt.executeQuery(" select user_name,password,dept_id,grade from    user_details ");
      while( rs.next() )
       {
          u=rs.getString("user_name");
          p=rs.getString("password");
          dept=rs.getString("dept_id");
          grade=rs.getString("grade");

          if (u.equalsIgnoreCase(userName) && p.equals(password) )
           {
               return 1;
           }
       }
     return 2;
    }
    catch(Exception e)
     {
       System.out.println(" catch of login beans");
       return 2;
     }
  }
}


Even after one user logs out and logs in with a different name then it displays the name of the previous user. This happens only when they both have the same grade otherwise it gives correct results.
The application is deployed on linux. This problem doesn't arise when the application is deployed on windows
it could be problem with browser cache

do one thing
put the following code in chearcache.inc and include it in all JSPs

<HEAD>

<META Http-Equiv="Cache-Control" Content="no-cache">
<META Http-Equiv="Pragma" Content="no-cache">
<META Http-Equiv="Expires" Content="0">

<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
<META HTTP-EQUIV="EXPIRES" CONTENT="0">
<%response.setHeader("Cache-Control","no-cache");response.setDateHeader("Expires",0);response.setHeader("Pragma","No-cache");response.setHeader("CACHE-CONTROL","NO-CACHE");response.setDateHeader("EXPIRES",0);response.setHeader("PRAGMA","NO-CACHE");%>
<META HTTP-EQUIV="EXPIRES" CONTENT="0">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CHACHE">
</HEAD>


and take care that it should be at top and bottom of your html

i.e

<%@ page include="clearcache.inc %">
<html>
other html stuff
</html>
<%@ page include="clearcache.inc %">

and one more thing you need to do is

rs=stmt.executeQuery(" select user_name,password,dept_id,grade from    user_details ");

modify the above statement to



rs=stmt.executeQuery(" select user_name,password,dept_id,grade from    user_details  where to_upper(user_name)='"+userName.toUpper()+"' and password='"+password+"'");

may be database side and jsp side uppercase methods are wrong. put appropriate methods there
and one more thing you need to do is

change the code like this in bean
public class LoginSubmitBean
{
 private  String userName,password;
 private  String u,p,dept,grade;
 private   Connection con=null;
 private   Statement stmt=null;
 private   ResultSet rs=null;

}


and access the information like this

bean.getUser() and bla bla bla
and one more thing you need to do in bean is
int flag=2; //initialise at starting of your method execution
      if (u.equalsIgnoreCase(userName) && p.equals(password) )
       {
               flag=1;
           }
       }
       flag=2;
    }
    catch(Exception e)
     {
       System.out.println(" catch of login beans");
     flag=2;
     }

close(con,stmt,rs);

return flag;

private satic void close(Connection c, Statement s, Resulset r)
{
     try
     {
               if(r!=null) r.close();     if(s!=null) s.close();     if(c!=null) c.close();
     }
     catch(Exception ex)
     {
     }
}
Still doesn't solve the problem
I can't get the private variables work. If I declare them private they r not accessible from jsp page.

Suggestion:
and access the information like this bean.getUser() and bla bla bla

Comment: But even in the code I have shown I am using bean.getUser() etc.
This problem is only coming when the application is deployed in Linux. There is no such problem with windows.
>> if (u.equalsIgnoreCase(userName) && p.equals(password) )
>>       {
>>               flag=1;
>>           }
>>       }
>>       flag=2;
sudhakar_koundinya, that's wrong, it end up with flag=2 always.

>>       user=loginSubmitBeanId.u;
steven, shouldn't it be:
user = loginSubmitBeanId.getUserName();

and try to expire the menu.jsp and addmenu.jsp page.
Changed loginSubmitBeanId.u to loginSubmitBean.getUserName()
but still doesn't help.
How can I expire menu.jsp ???
<% response.setHeader("pragma", "no-cache");
response.setHeader("Cache-control", "no-cache, no-store, must-revalidate");
response.setHeader("Expires", "01 Apr 1995 01:10:10 GMT"); %>
I am already including the file clearcache.inc as suggested by sudhakar_koundinya. Isn't that sufficient??
The value that comes out of the bean is  the right one. It's the session attribut that refuses to go even when I have used remove attribute.
steven,
 i have faced the same problem earlier. session.setAttribute(), session.getAttribute() and session.removeAttribute() just refuse to work sometimes.
 I suggest a much better option here.something that has worked for me when i have ported my application from a windows environment to a solaris enviroment. Hope it works for u as well.
 Use, session.putValue(),getValue() and removeValue(). Although depricated it gives 100% success.
 So if u have an attribute say "name".
session.putValue("name","Deepak");

session.getValue("name");

When u wanna remove this stuff.
session.putValue("name",null);
session.removeValue("name");
session.invalidate();

Having said this, assuming that u have put that pragma-no cache code in ur header, u need to make/select one last setting on ur browser.

tools >> internet options >> settings >>  every visit to the page.


Lemme know how it goes...



Even this doesn't work
Its very strange. On some pages it shows the correct session value, on others it shows the previous users value.
 How can one session variable store 2 different values at the same time???
Its very strange. On some pages it shows the correct session value, on others it shows the previous users value.
 How can one session variable store 2 different values in the same session????
this is so trouble some!
Plz give some more suggestions.
Strange,

I have n't faced any problem using session.putAttribute or session.getAttribute

:-(
one more suggestion

though it is not necessary, just we try for this also

you are saying session=request.getSession(true);
temperorly comment this code , as you are invalidating the session in logout page
if the above doesn't work

do like this

if(session==null)
{
    session=request.getSession(true);
}


Thanks for ur reply Sudhakar.
Are u using Linux?
This problem comes only in Linux and not in windows. Even deepak had this problem in Solaris.
Wonder what's the reason
;)
Done that already, Sudhakar
even with putValue also i am not facing any problem
yes i am testing the sessions in both environments win2000 and redhat linux 7.1
GOD HELP
>> Its very strange. On some pages it shows the correct session value, on others it shows the previous users value.
 How can one session variable store 2 different values at the same time???


i want to see the code snippets of both pages, if you have no problem with that :-)
After Deepak's suggestion I changed to put and get values but the same problem is with get and set attributes. Here the code i am showing has put and get.

Here is the login page.
loginSubmit.jsp
<%@ include file="clearcache.inc" %>
 
<html>
<head><title>Login Submit</title></head>

<%String userName=request.getParameter("userName");%>
<%String password=request.getParameter("password");%>
<jsp:useBean id="loginSubmitBeanId" scope="page" class="approval.LoginSubmitBean" />

<jsp:setProperty name="loginSubmitBeanId" property="*" />
<body bgcolor="#ffffff">
<%!
   String user;
   String dept;
   String pwd;
   String grade;
%>

<%
          session.putValue("user",null);
     session.removeValue("user");
       session.putValue("dept",null);
     session.removeValue("dept");
     session.putValue("grade",null);
     session.removeValue("grade");

   int val=loginSubmitBeanId.authenticate();
   if(val==1)
    {
    //  user=loginSubmitBeanId.u;
      user=loginSubmitBeanId.getUserName();
        pwd=loginSubmitBeanId.getPassword();
      dept=loginSubmitBeanId.dept;
      grade=loginSubmitBeanId.grade;

      session=request.getSession();

      session.putValue("user",user);
      session.putValue("dept",dept);
      session.putValue("grade",grade);

    if(grade.equals("3") || grade.equals("1"))
            {
         response.sendRedirect("menu.jsp");
            }
     if(grade.equals("2"))
            {
               response.sendRedirect("adminMenu.jsp");
            }
 
  }
  else
  {
    response.sendRedirect("loginFailed.jsp");
  } %>

</body>
</html>
<%@ include file="clearcache.inc" %>
-----------------------------------------------------------------------------------
And here goes LoginSubmitBean.java

package approval;
import java.sql.*;

public class LoginSubmitBean
{
  private String userName,password;
  public String u,p,dept,grade;
  private Connection con=null;
  private Statement stmt=null;
  private  ResultSet rs=null;

  public String getUserName()
  {
    return userName;
  }

  public void setUserName(String userName)
  {
       this.userName = userName;
  }
  public String getPassword()
   {
     return password;
   }

   public void setPassword(String password)
   {
        this.password = password;

   }
  public int authenticate()
  {
     int flag=2;
       try
     {
      p=" ";
      u=" ";
      dept=" ";
      grade=" ";

      Class.forName("org.gjt.mm.mysql.Driver");
      con=DriverManager.getConnection("jdbc:mysql://localhost/a");
      stmt=con.createStatement();
      rs=stmt.executeQuery("SELECT user_name,password,dept_id,grade FROM user_details WHERE upper(user_name)='"+userName.toUpperCase()+"' and password='"+password+"'");

      while( rs.next() )
       {
          u=rs.getString("user_name");
          p=rs.getString("password");
          dept=rs.getString("dept_id");
          grade=rs.getString("grade");

          if (u.equalsIgnoreCase(userName) && p.equals(password) )
           {
               flag=1;
                   //  return flag;
           }
       }

    }



    catch(Exception e)
     {
       System.out.println(" catch of login beans");
       flag=2;
     }
 close(con,stmt,rs);
 return flag;

 
  }

  private static void close(Connection c, Statement s, ResultSet r)
   {
     try
     {
               if(r!=null){ r.close();}  
              if(s!=null){ s.close();}    
                     if(c!=null){ c.close();}
     }
     catch(Exception ex)
     {
       }
   }
}
-----------------------------------------------------------------------
Here is the menu.jsp page where the name of user is displayed and it displays out to be the current one.

<% response.setHeader("pragma", "no-cache");
response.setHeader("Cache-control", "no-cache, no-store, must-revalidate");
response.setHeader("Expires", "01 Apr 1995 01:10:10 GMT"); %>

<%@ include file="clearcache.inc" %>
<%@ page language="java" import="java.sql.*" %>
<html>
<head>
   <title>Menu</title>
 </head>
<body>

<%      
 
   String user=(String)session.getValue("user");
   String dept=(String)session.getValue("dept");
   
   Class.forName("org.gjt.mm.mysql.Driver").newInstance();
   Connection con=DriverManager.getConnection("jdbc:mysql://localhost/a");
   Statement stmt=con.createStatement();
   ResultSet rs= stmt.executeQuery("SELECT dept_name FROM dept WHERE dept_id='"+dept+"' ");
   rs.next();
      String dept_name = rs.getString("dept_name");
  %>
          </tr>

              <tr><td align="center" ><u><font color=red><b>Welcome</B></font></u>
              <p>&nbsp;&nbsp;&nbsp;User:<font color="#000080"><b><i>&nbsp;&nbsp;<%=user%></i></b></font>
              <p>Dept:<font color="#000080"><b><i>&nbsp;<%=dept_name%></i></b></font></td></tr>
       


       </table>
         </td>
  </tr>
 </table>
</body>
</html>

---------------------------------------------------------------------------
Here is another page  inbox.jsp which displays user name of previous session.

inbox.jsp

<%@ page import="java.util.*" %>

<meta http-equiv="Page-Enter" content="revealtrans(duration=1,transition=8)">

<html>
<head>
  <META HTTP-EQUIV="Content-Style-Type" CONTENT="text-css" >
  <LINK REL="STYLESHEET" HREF="cssApproval.css" >
</head>

<%!
       ResultSet rs = null;
       Statement stmt = null;
       int count=0;
       int ctr = 0;
       String indentno;
       String itemno;
%>
<%@ include file="db.jsp" %>      
<body bgcolor="#ffffff">
<% if(request.isRequestedSessionIdValid() )
      {
%>

  <jsp:include page="menu1.jsp" />
<%
   String user=(String)session.getValue("user");
   stmt = con.createStatement();

   %>
  <FORM NAME="form1">
   <TABLE width="100%" class=tableMain>
  <thead>
       <TR>
          <TD COLSPAN=5 align=center>Inbox of <%=user%></TD>
        </TR>
       <TR>
         <TH class=tableHead><a href="#" onclick="TableSort('inventory1', 0, 'n')">Indent No</a></TH>
         <TH class=tableHead><a href="#" onclick="TableSort('inventory1', 1, 'ai')">Send By</a></TH>
         <TH class=tableHead><a href="#" onclick="TableSort('inventory1', 2, 'de')">Date</a></TH>
         <TH class=tableHead><a href="#" onclick="TableSort('inventory1', 3, 'ai')">Dept</a></TH>
         <TH class=tableHead><a href="#" onclick="TableSort('inventory1', 4, 'ai')">Remarks</a></TH>

     </TR>
  </thead>
      <tbody id="inventory1">

   <%
        ctr=0;
       rs=stmt.executeQuery("SELECT indentNo, user, currentDate,dept.dept_name FROM approval.indent,a.dept WHERE indent.dept = dept.dept_id AND indent.sendTo='"+user+"'");
        while(rs.next())
          {
            indentno =  rs.getString("indentNo");
            ctr++;
                  
%>
            <TR>
               <TD class=tdMain><%=indentno%></TD>
               <TD class=tdMain><%=rs.getString("user")%></TD>
               <TD class=tdMain><%=rs.getString("currentDate")%></TD>
               <TD class=tdMain><%=rs.getString("dept_name")%></TD>
               <TD class=tdMain>Add</TD>
                     <TD class=tdMain><a href="details.jsp?indentNo=<%=indentno%>">Details</a></TD>
             
                  </TR>
        <%
           }
       rs=stmt.executeQuery("SELECT indentno, itemno, user, currentDate,dept.dept_name FROM approval.tempcloseditems, a.dept WHERE tempcloseditems.dept = dept.dept_id AND visibility=1");
       while(rs.next())
          {
               ctr++;
               indentno = rs.getString("indentno");
                 itemno = rs.getString("itemno");
             %>
            <TR>
              <TD class=tdMain><%=indentno%></TD>
              <TD class=tdMain><%=rs.getString("user")%></TD>
              <TD class=tdMain><%=rs.getString("currentDate")%></TD>
              <TD class=tdMain><%=rs.getString("dept_name")%></TD>
              <TD class=tdMain>Received</TD>
                  <TD class=tdMain><a href="detailsReceived.jsp?indentNo=<%=indentno%>&itemNo= <%=itemno%>">Details</a></TD>
           </TR>
             <%
           }
      if(ctr==0)
              { %>
                <TR><TD COLSPAN=5 align=center>No Records To Display</TD></TR>
             <% }
%>
  </tbody>
</TABLE>

</form>
<%}
          else  { %>            <center>
                <H3>NOT A VALID SESSION
                  <BR>PLEASE <a href="index.html">click here</a>TO LOG IN
                                    <%  }  %>


</body>
</html>
-----------------------------------------------------------------
Another thing I'd like to mention here.
I have given grades to  every user. The problem arises if the grades of both the users are same not when the grades are different.
Take for example.
First user andrew logs in and his grade is 1.
He logs out and then sohan logs in his grade is also 1. Now in inbox.jsp it will display "Inbox of Andrew" although in the menu.jsp it'll display "Welcome  Sohan".
But instead of Sohan if Joe logs in and his grade is 2, correct results will be disaplyed in all the pages.
No such problem arises in window its only when app is deployed in Linux
i have n't find <%@ include file="clearcache.inc" %> in inbox.jsp

try to put that and let me know
regards
here is the code for logout.jsp


<%@ page language="java" import="java.sql.*" %>
<%@ include file="clearcache.inc" %>      
<HTML>
<BODY>
<CENTER>

<%
  session.putValue("user",null);
  session.removeValue("user");

  session.putValue("dept",null);
  session.removeValue("dept");
 
  session.putValue("grade",null);
  session.removeValue("grade");
 
  session.invalidate();
 
  response.sendRedirect("index.html");
   %>
</BODY>
</HTML>
IF THE ABOVE WORKS MEANS CHANGE THE CODE TO SETATTRIBUTE METHODS AND TEST AGAIN AS PUTVALUE METHODS ARE DEPRICATED
AS SUGGESTED PREVIOUSLY PUT THE INCLUDE STATEMENT AT THE TOP AND BOTTOM OF HTML CODE IN INBOX.JSP
HELLO,

is that new suggestion helps you?
ASKER CERTIFIED SOLUTION
Avatar of sudhakar_koundinya
sudhakar_koundinya

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hey that does it.
Thanks a lot. u r gr8.
Finally its done.
U deserve more than 390 points but that is all i have at the moment.
;)
Thanks to everyone who participated in the discussion.