How do I track users

l_starter_l
l_starter_l used Ask the Experts™
on
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..
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
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.

Author

Commented:
You mean encode the username with a cookie?
Murali MurugesanFull stack Java developer

Commented:
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

Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

Author

Commented:
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

Murali MurugesanFull stack Java developer

Commented:
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*

Author

Commented:
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
Murali MurugesanFull stack Java developer

Commented:
can u try printing the value in ur index.jsp and see what it prints,

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

Author

Commented:
it prints the username..

Author

Commented:
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

Murali MurugesanFull stack Java developer

Commented:
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*

Author

Commented:
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?
Murali MurugesanFull stack Java developer

Commented:
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*

Author

Commented:
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

Murali MurugesanFull stack Java developer

Commented:
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.

Author

Commented:
yes I have
 HttpSession session = request.getSession();
Full stack Java developer
Commented:
Fine. Few steps to troubleshoot,

1. If you are using eclipse place a breakpoint in the session invalidation code and see if the session is really invalidated.

2. Or just have a System.out.println statement next to session.invalidate() and print the  value session.getAttribute("userName");

Are you sure when clicking on logout , your session.invalidate() code is triggered?

Try to change your code as below,



String logout = request.getParameter("logout");
HttpSession session = request.getSession();
 
if(logout == null && userName.equals(request.getParameter("user"))
                                     && passwrd.equals(request.getParameter("pass")))
                                {
									session.setAttribute("username",userName);
									response.sendRedirect("index.jsp");                                                                                                                             
 }else{
	  session.invalidate();
	  System.out.println("You have been logged out.");
	  response.sendRedirect ("AuthenticLogin.jsp");
 }

Open in new window

Author

Commented:
thank you got it working

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial