Solved

Problem in JSP sessions

Posted on 2003-11-21
39
1,706 Views
Last Modified: 2010-04-01
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
0
Comment
Question by:steven_fl
  • 18
  • 18
  • 2
  • +1
39 Comments
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
<%
// 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
}
%>
0
 

Author Comment

by:steven_fl
Comment Utility
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.
0
 

Author Comment

by:steven_fl
Comment Utility
The application is deployed on linux. This problem doesn't arise when the application is deployed on windows
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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 %">

0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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)
     {
     }
}
0
 

Author Comment

by:steven_fl
Comment Utility
Still doesn't solve the problem
0
 

Author Comment

by:steven_fl
Comment Utility
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.
0
 

Author Comment

by:steven_fl
Comment Utility
This problem is only coming when the application is deployed in Linux. There is no such problem with windows.
0
 
LVL 14

Expert Comment

by:kennethxu
Comment Utility
>> 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.
0
 

Author Comment

by:steven_fl
Comment Utility
Changed loginSubmitBeanId.u to loginSubmitBean.getUserName()
but still doesn't help.
How can I expire menu.jsp ???
0
 
LVL 14

Expert Comment

by:kennethxu
Comment Utility
<% 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"); %>
0
 

Author Comment

by:steven_fl
Comment Utility
I am already including the file clearcache.inc as suggested by sudhakar_koundinya. Isn't that sufficient??
0
 

Author Comment

by:steven_fl
Comment Utility
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.
0
 
LVL 1

Expert Comment

by:deepak_a
Comment Utility
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...



0
 

Author Comment

by:steven_fl
Comment Utility
Even this doesn't work
0
 

Author Comment

by:steven_fl
Comment Utility
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???
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:steven_fl
Comment Utility
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????
0
 

Author Comment

by:steven_fl
Comment Utility
this is so trouble some!
Plz give some more suggestions.
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
Strange,

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

:-(
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
if the above doesn't work

do like this

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


0
 

Author Comment

by:steven_fl
Comment Utility
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
;)
0
 

Author Comment

by:steven_fl
Comment Utility
Done that already, Sudhakar
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
even with putValue also i am not facing any problem
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
yes i am testing the sessions in both environments win2000 and redhat linux 7.1
0
 

Author Comment

by:steven_fl
Comment Utility
GOD HELP
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
>> 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 :-)
0
 

Author Comment

by:steven_fl
Comment Utility
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
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
i have n't find <%@ include file="clearcache.inc" %> in inbox.jsp

try to put that and let me know
regards
0
 

Author Comment

by:steven_fl
Comment Utility
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>
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
IF THE ABOVE WORKS MEANS CHANGE THE CODE TO SETATTRIBUTE METHODS AND TEST AGAIN AS PUTVALUE METHODS ARE DEPRICATED
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
AS SUGGESTED PREVIOUSLY PUT THE INCLUDE STATEMENT AT THE TOP AND BOTTOM OF HTML CODE IN INBOX.JSP
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
HELLO,

is that new suggestion helps you?
0
 
LVL 14

Accepted Solution

by:
sudhakar_koundinya earned 390 total points
Comment Utility
in every page you need to put <%@ include file="clearcache.inc" %> this code at top and bottom of the pages
0
 

Author Comment

by:steven_fl
Comment Utility
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.
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
Great :-)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

HOW TO: Connect to the VMware vSphere Hypervisor 6.5 (ESXi 6.5) using the vSphere (HTML5 Web) Host Client 6.5, and perform a simple configuration task of adding a new VMFS 6 datastore.
Find out what Office 365 Transport Rules are, how they work and their limitations managing Office 365 signatures.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now