Solved

Session attribute problem

Posted on 2004-04-06
6
485 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:Mayank S
ID: 10772175
Perhaps you can try: HttpSession session = req.getSession ( false ) != null ? req.getSession ( false ) : req.getSession ( true ) ;
0
 
LVL 30

Expert Comment

by:Mayank S
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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:Mayank S
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
JspWriter.write() and JspWriter.print() 4 81
password protect pdf 11 74
java.util.concurrent.Callable way of creating threads 2 102
oracle fusion vs MQ 2 107
Citrix policies are the most efficient method to configure and tune XenDesktop environments, allowing organizations to control connection, security and bandwidth settings based on various combinations of users, devices or connection types.  Citrix …
Often, people trade privacy and security for convenience. However in today's concrete jungle, this is an extremely foolish decision considering the vast amount of technologies being used against consumer interest. First off, I won't waste any time e…
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

937 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

15 Experts available now in Live!

Get 1:1 Help Now