• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 495
  • Last Modified:

Session attribute problem

Hi,

I am using tomcat 4.1.29, html to log in, jsps and servlets for my application.

In the application I would like to enable a user to log in with a user name but after a check against my database I want the user name and their surname to be displayed on the page for the whole time until they log out form the application or just close the browser.

I have managed to get the sql query right.  The name appears in the header of my jsp.  The home page is as follows


<%@ page session = "true"
      import="java.util.*, java.sql.*,
            java.lang.*"%>

<html>

<head>
<title>Home Page</title>
<link rel=stylesheet href="x.css" type="text/css">
</head>

<% String name, surname;

      name = (String)session.getAttribute("name");
      surname = (String)session.getAttribute("surname");
%>

<body>
<table border="0" width="100%">
      <tr>
            <td colspan="2"><jsp:include page="Titlebar.jsp" flush="true" /></td>
      </tr>
      <tr>
            <td width="15%"><%@ include file="Sidebar.jsp" %></td>
            <td valign="center" ><div><h2>Welcome to the Main Page</h2></div></td>

      </tr>
</table>
</body>

</html>

When I log in for the first time, all is working correctly.  But the problem begins when I log out and try to log in again.  I am getting an Exceptions java.sql.SQLException: General error .

I found out that when I restart Tomcat and log in again it works fine again. But...
If I log in with another user name, the name of the prevoiusly logged user appears on further pages, but not on the home page.  Is it a problem with the session attribute?  I am enclosing my login servlet below

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;

public class Indexloginservlet1 extends HttpServlet {
      
      Connection con = null;
      
      public void init() {
            try{
                   //load the JDBC driver
                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

                  //Connects to the DB
                  String url = "jdbc:odbc:Publisher";
                  String user = "";
                  String password = "";
                  con = DriverManager.getConnection(url,user,password);
            } catch (Exception e) {
                  System.out.println("Exceptions in init " + e);
            }
      }

      public void destroy() {
            try{
                  //Disconnects DB
                  con.close();
            } catch (Exception e) {
                  System.out.println("Exceptions " + e);
            }
      }

      public void doPost(HttpServletRequest req,HttpServletResponse res)
      throws IOException,ServletException {

    // get parameter from login.html
      String username = req.getParameter("username");
      String password = req.getParameter("password");

      res.setContentType("text/html");

      PrintWriter out = res.getWriter();

      try
      {
            HttpSession session = req.getSession(true);
            Statement stmt = con.createStatement();
        // check longin information
       
            String query;
            
            if(username.equals("") && password.equals(""))
            {
                  String htmlPath = "/TaxiGlobe/index.html";
                  out.println("<html><body>");
                  out.println("<h2>Error! -- No data entered.</h2>");
                  out.println("<center>");
                  out.println("<p>Please press <a href='"+htmlPath+"'><b>Back<b></a> to re-enter your login and password");
                  out.println("</center>");
                  out.println("</body></html>");
                  
            }else
            {
                  query = "SELECT EmplName, EmplSurname, Login,Password FROM Staff";
                  query += " where Login ='"+username+"' AND Password = '"+password+"' ";
                  
            

            ResultSet login_rs = stmt.executeQuery(query);
            
        // if login successful allow the user to enter the system
       
            if (login_rs.next())
            {
                        
                  //out.println("Employee name: " + login_rs.getString("EmplName"));
                  String name = login_rs.getString("EmplName");
                  String surname = login_rs.getString("EmplSurname");
                  
                  
                  session.setAttribute ("username", username);
                  session.setAttribute ("password", password);
                  session.setAttribute ("name", name);
                  session.setAttribute ("surname", surname);
                  session.setAttribute ("Search", new Boolean(false));
                  
                  // redirect the user to the home page
                  try {
                        res.sendRedirect("/TaxiGlobe/Home.jsp");
                        }
                        catch (Exception e) {
                              out.println("<html><body>");
                              out.print(" Could not redirect the page " + e);
                              out.println("</body></html>");
                        }

      
            }else

            // if user name and password are not valid, produce error page
            {

      
                  //PrintWriter out = res.getWriter();
                  String htmlPath = "/TaxiGlobe/index.html";
                  out.println("<html><body>");
                  out.println("<h2>Error! -- Invalid user name or password. </h2>");
                  out.println("<center>p>Please press <a href='"+htmlPath+"'><b>Back<b></a> to re-enter the user name and password!!");
                  out.println("</center>");
                  out.println("</body></html>");
                  out.close();

            }

            login_rs.close();
            stmt.close();
            con.close();
     }

      }

      catch (Exception e)
            {

                        //PrintWriter out = res.getWriter();
                        out.println("<html><body>");
                        out.println("<p>Exceptions, " + e);
                        out.println("</body></html>");

            }
      }
}

I will really appreciate any help and suggestions.  

Thank you

0
11pm
Asked:
11pm
1 Solution
 
Mayank SAssociate Director - Product EngineeringCommented:
Perhaps you can try: HttpSession session = req.getSession ( false ) != null ? req.getSession ( false ) : req.getSession ( true ) ;
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Maybe you can also remove: session = "true" from @page and see what happens with that.
0
 
jarasaCommented:
If you log out you must invalidate the session with seesion.invalidate() if not you will still have the same session as long as you don't close the browser and open a new one, have you tryed that?

Opening a new browser and login again? if you use IE it will create a new session if your're using NS or Mozzilla you must close the previous browsers.

Javier
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
11pmAuthor Commented:
First problem which I had is sorted.  I released that <%@ page session = "true"
     import="java.util.*...  %> was missing on the rest of my pages, and that's why the name from the previous session kept appearing.  Thank you mayankeagle.


I've invalidated session with logout servlet, but I am not sure if it works. When I selects Logout from the main page the servlet invalidates the session and redirects the flow to the login page.  
But...
When I log in again I am getting this error:

Exceptions, java.sql.SQLException: General error

This is the last catch clause.  Is there some connection which is not closed or is it still the session problem?

When I open another browser window and try to log in, it doesn't let me.  I am agetting the above error straight away.

Can anyone help?

 
0
 
bcassandCommented:
It seems that you close the database connection when the login is done:
    ...
    login_rs.close();
    stmt.close();
    con.close();
    ...

Closing the Statement is ok, but as the connection is created when the servlet is initialized, if tomcat is not restarted, on the second login, when you try to use the connection, an error happened.
Just try to comment the con.close(); line.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
11pm,

Do you know that you can split the points between experts if one helped you with one part of the problem and another helped you with a second part?
0

Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now