Solved

Session attribute problem

Posted on 2004-04-06
6
490 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Getting to know the threat landscape in which DDoS has evolved, and making the right choice to get ourselves geared up to defend against  DDoS attacks effectively. Get the necessary preparation works done and focus on Doing the First Things Right.
With the rising number of cyber attacks in recent years, keeping your personal data safe has become more important than ever. The tips outlined in this article will help you keep your identitfy safe.
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
Suggested Courses

623 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