Solved

Session attribute problem

Posted on 2004-04-06
6
484 Views
Last Modified: 2010-08-05
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
Comment
Question by:11pm
6 Comments
 
LVL 30

Expert Comment

by:mayankeagle
ID: 10772175
Perhaps you can try: HttpSession session = req.getSession ( false ) != null ? req.getSession ( false ) : req.getSession ( true ) ;
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 10772183
Maybe you can also remove: session = "true" from @page and see what happens with that.
0
 
LVL 6

Expert Comment

by:jarasa
ID: 10772918
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:11pm
ID: 10793518
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
 

Accepted Solution

by:
bcassand earned 50 total points
ID: 10794771
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
 
LVL 30

Expert Comment

by:mayankeagle
ID: 10803711
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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Is your Office 365 signature not working the way you want it to? Are signature updates taking up too much of your time? Let's run through the most common problems that an IT administrator can encounter when dealing with Office 365 email signatures.
For cloud, the “train has left the station” and in the Microsoft ERP & CRM world, that means the next generation of enterprise software from Microsoft is here: Dynamics 365 is Microsoft’s new integrated business solution that unifies CRM and ERP fun…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

747 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

12 Experts available now in Live!

Get 1:1 Help Now