Solved

Session attribute problem

Posted on 2004-04-06
6
487 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
Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

 

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

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Fisheye tool 2 111
struts exact match support 3 56
Using Tomcat as raspberry pi java app server 13 166
Why my table column Id is not passed to java object? 4 39
In this article we will learn how to backup a VMware farm using Nakivo Backup & Replication. In this tutorial we will install the software on a Windows 2012 R2 Server.
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

822 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