Link to home
Start Free TrialLog in
Avatar of l_starter_l
l_starter_lFlag for United States of America

asked on

How do I track users

Hi,
I have a login servlet that authenticates users with a database of valid username and password with they are valid they are redirected to the index page.. The servlet works fine..
Now I am wondering how do I track a user for example a user logins in and stays loggged in until they log out or the session expires..
Also how do I configure it so that users cannot access the index..directly..e.g. if they put in the path of the index page they can do their directly without even logging in.. can tell me how or give me an example of this?? This will all be done with servlets..
Avatar of Muhammad Khan
Muhammad Khan
Flag of Canada image

you can have a check on index page that verifies that your username session variable has some value in it.. if it doesn't. .then redirect the user to login page...

if you have an explicit logout method.. (ie clicking on a link to logout) then you can code a logout procedure that writes the log out event to your dtabase for that session... that way you can track when user came in.. .and when he left.
Avatar of l_starter_l

ASKER

You mean encode the username with a cookie?
Use HttpSessionListener. So every time a user logs in a new session is created and you cn insert a record for user tracking. On logout /session expiry a listener method is triggered  where u can again track the user going out.

something like the code snippet,

For restricting access,

at the top of the index.jsp check for some session attribute != null. Say on login u set the "userId" attribute with the logged in user id. So u check for it in the index.jsp. Something like this


<%if(session.getAttribute("userId") != null){%>

-- index page contents
<%}else{%>
Please login to the application. <a href="login.jsp">Click Here to Login</a>
<%}%>

-Murali*
public class SessionListener implements HttpSessionListener {
 
  public void sessionCreated(HttpSessionEvent event) {
    //track new user
  }
 
  public void sessionDestroyed(HttpSessionEvent event) {
    // user going out by logout or session expiry.
  }
}

Open in new window

hi can you give me an example using this code... where do i put the session object..and how do I code it?
package login;
 
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class LoginAuthentication extends HttpServlet{
 
  private ServletConfig config;
 
  public void init(ServletConfig config)
    throws ServletException{
     this.config=config;
     }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
              throws ServletException,IOException{
 
    PrintWriter out = response.getWriter();
    String connectionURL = "jdbc:odbc:project";
    Connection connection=null;
    ResultSet rs;
    String userName=new String("");
    String passwrd=new String("");
    response.setContentType("text/html");
 
      try
			{
				// Load the database driver
				Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
				// Get a Connection to the database
				connection = DriverManager.getConnection(connectionURL, "", "");
				// Add the data into the database
				String sql =
				    "SELECT user,password FROM USER_INFO WHERE user='"
				    + request.getParameter("user") + "'" + "AND password='" + request.getParameter("pass") + "'";
 
                                Statement s = connection.createStatement();
				s = connection.createStatement();
				rs = s.executeQuery(sql);
                                HttpSession session = request.getSession(true);
 
                                while (rs.next())
				{
					userName = rs.getString("user");
					passwrd = rs.getString("password");
				}
 
				if(userName.equals(request.getParameter("user"))
			             && passwrd.equals(request.getParameter("pass")))
				{
//                                   session.setAttribute("username",name);
//                                    String string = response.encode
//                                    URL("NextPageAfterFirst.jsp?name=+name+&password=+password");
                                   response.sendRedirect("index.html");
 
                                }
			    else
			    {
			        out.println("Please enter correct username and password");
			        out.println("<a href='AuthenticLogin.jsp'><br>Login again</a>");
			    }
 
 
                                        rs.close();
					s.close();
			}
			catch (Exception e)
			{
				System.out.println("Exception is ;" + e);
			}
			finally
			{
				try
				{
					connection.close();
 
 
				}
				catch (SQLException ex)
				{
					System.out.println("Exception is ;" + ex);
				}
			}	}}

Open in new window

Uncomment line 52,

                                   session.setAttribute("username",name);

rename the index.html file to index.jsp

response.sendRedirect("index.jsp");

In index.jsp do this,

<%if(session.getAttribute("username") != null){%>
<html>
       <head></head>
      <body> Hello World</body>
</html>
<%}else{%>
        <a href="/login.jsp">Click here to Login</a>
<%}%>

-Murali*
I have done this..but it works the same way..How do I prevent a user from accessing the index directly making them always have to go to the login page
can u try printing the value in ur index.jsp and see what it prints,

System.out.println(session.getAttribute("username"));

it prints the username..
what I need is to stop users from access the pages directly..if they try redirect them to the login page..
But right now if I put in the Index.jsp url I can still get there without being redirected..
Do I need to user url encoding for that??
How do I use it if I have to

it prints the username..

>> then you already have the session active with user id.
Always do session.invalidate(); in logout page.
Close the browser and open a new one and try accessing the index.jsp, it should work.

Do I need to user url encoding for that??

>> I dont think u need to use url encoding for a simple redirection. A simple redirect would do.
But first make sure the index.jsp is not accessible by doing the above steps.

-Murali*
How do I use session invalidate..
If I have a logout button on my page..how do I code that..
Does the code go on the page or in the servlet?
It depends whether to have it on JSP or Servlet.
Since u have a logout button you must submitting the click to some servlet, so in servlet you can have something like this before re-directing to the login.jsp.

session.invalidate();
//thn redirect to login.jsp

-Murali*
I did it like but it doesnt remove the session.. the user stays logged in..
if(userName.equals(request.getParameter("user"))
			             && passwrd.equals(request.getParameter("pass")))
				{
                                    String logout = request.getParameter("logout");
                                   HttpSession session = request.getSession();
                                    if (logout==null)
                                    {
                                    
                               session.setAttribute("username",userName);
                                 response.sendRedirect("index.jsp");
                                    }
                                 else{
 
                                     session.invalidate();
//                                     session.removeAttribute("username");
//                                     out.println("You have been logged out.");
//                                     response.sendRedirect ("AuthenticLogin.jsp");
                                 }}
                                

Open in new window

check whether you have some code like request.getSession(true); bcoz this would create a new session if there is not an already existing session.
yes I have
 HttpSession session = request.getSession();
ASKER CERTIFIED SOLUTION
Avatar of Murali Murugesan
Murali Murugesan
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thank you got it working