Link to home
Start Free TrialLog in
Avatar of hewu
hewu

asked on

who's accessing my system in jsp?

Does anyone know how to implement a jsp program which can identify who's online at the moment? I search for long time and can't find any jsp source code.I want to know their number, ip address and even their current status(such as which pages they are). Help appreciated!

   Wu
Avatar of Mick Barry
Mick Barry
Flag of Australia image


Add some code to all your pages to store details required from the incoming request.
Avatar of hewu
hewu

ASKER

Thanks.But I don't understand it.I am not so experienced.
I want to know who's online and display thier ip address.
That's it. Can you explain it more detailedly and give me some codes to analyze?

   Wu

       
Have a look at the ServletRequest class, and in particular the headers included with it. This should include most of the the information you require.
The bottom line is you need to track whose online yourself by analyzing details of all incoming requests.
I agree with objects.  have like an application level counter that tracks how many users are on the system.  each request can be uniquely identified so no user gets counted twice.

CJ
instead of change every jsp page, one Filter class can handle it and handle it better. a Filter class will receive any request before it reach you jsp page, so you can easily do you counting in one central place.

this is a tutorial of Filter, although it is for Orion server, the concept applys to any servlet 2.3 comply servers.
http://www.orionserver.com/tutorials/filters/1.html
>I want to know who's online and display thier ip address

How about using a listener?

import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
public class SessionCounter implements HttpSessionListener {
   public void sessionCreated(HttpSessionEvent event) {
       // here is where you can add user's ip address to a data structure
   }
   public void sessionDestroyed(HttpSessionEvent event) {
      // here is where you can remove a user
   }
}

rrz, i don't think you can determine user's ip address from HttpSessionEvent. correct me if i'm wrong.
I too agree with Objects.  For my main jsp entry page i create a record in a database (containing ip address, time of login, login type[in], and finally expirytime of session in seconds).  This way you can always expand the system for login/logout, time online, average time spent on system.

To Kenneth,
Good point! But maybe the solution involves both Filter and Listener classes.
The filter to get the ip address and the listener to remove it from the list of current users.
Or maybe use one object to implement both?
Avatar of hewu

ASKER

Thanks all of you. There are great points here.
As my system has many pages, I am not going to add codes for each page.I just want to write a jsp page and then  showes which IPs are online. It's a good point to create a record in a database (containing ip address, time of login, login type[in], and finally expirytime of session in seconds).Who can show me how to do that? Thanks.

 
Avatar of hewu

ASKER

Want to clarify a point.My purpose is to write a jsp page so that I can check who's accessing my system.I think I have to check how maqny session objects there are at this moment and then analyze their ip address and eliminate the repeated ip . Am I on a right track? Any other ideas or codes to finish this task?Thanks.

  Wu
My dear friends,
The HttpServletRequest object has two beautiful methods getRemoteAddr() and getRemoteHost() to get the IP address of client. Infact spending sometime with JSP/Servlet API wouldn't be a bad idea :) I think objects clarified that in the very begining of this thread.

However a word of caution here: if the client is behind a firewall or proxy server, this IP address will most probably be that and not the clients machines address.
 
Regards,
Debashish
use a filter class:
http://java.sun.com/products/servlet/Filters.html
http://www.fawcette.com/javapro/2002_02/magazine/features/kjones/default_pf.asp
http://www.javaworld.com/javaworld/jw-06-2001/jw-0622-filters.html
http://www.orionserver.com/tutorials/filters/1.html

This has a sample code of using HttpSessionListener to count users:
http://www.fawcette.com/javapro/2002_02/magazine/features/bkurniawan/default_pf.asp  [listing 6]

or try a filter class like this:

package com.yourcompany.filter;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class UserCounter implements Filter {
  FilterConfig config;

  public void setFilterConfig(FilterConfig config) {
    this.config = config;
  }

  public FilterConfig getFilterConfig() {
    return config;
  }

  public void doFilter(ServletRequest req,
                       ServletResponse res,
                       FilterChain chain) {
    ServletContext context = getFilterConfig().getServletContext();
    Integer userCount = (Integer) context.getAttribute("UserCount");
    HttpSession session = req.getSession(true);
    Boolean hasBeenCounted = session.getAttribute("HasBeenCounted");
    // if this session var doesn't exist this user has not been counted yet
    if (HasBeenCounted == null) {
      if (userCount == null) {
        userCount = new Integer(1);
      }
      else {
        userCount = new Integer(userCount.intValue() + 1);
      }
      session.setAttribute("HasBeenCounted", new Boolean(true));
      context.setAttribute("UserCount", userCount);
    }
    chain.doFilter(req, res);  // no chain parameter needed here
  }
}

you have to add this to your web.xml of your application:
    <filter>
        <filter-name>UserCounter</filter-name>
        <filter-class>com.yourcompany.filter.UserCounter</filter-class>
        <description>
            This filter counts the number of users online using session and application variables.
        </description>
    </filter>
    <filter-mapping>
        <filter-name>UserCounter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


you need to deploy the filter to your webapp/WEB-INF/classes directory or in your war or a jar that your app uses.

to display the number of users online do this:

ServletContext context = getServletConfig().getServletContext();

Integer numOfUsers = (Integer) context.getAttribute("UserCount");


Its a very basic and simple implementation.  You can fiddle/fine tune and make it much more efficient and/or complex as you need it.

HTH,
CJ
ASKER CERTIFIED SOLUTION
Avatar of rrz
rrz
Flag of United States of America 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
hewu, what server and version are you using? Filters and Listeners requires Servlet 2.3

rrz, put context.setAttribute("usersbean",new Hashtable()); in Filter init to avoid concurrent issue, and keep a reference to usersbean to avoid unnecessary retrieve back.

and dont' forget to set sessin timeout in web.xml
Kenneth,
>put context.setAttribute("usersbean",new Hashtable()); in Filter init
good idea.
>keep a reference to usersbean
ok
>set sessin timeout in web.xml
I just used
><% session.setMaxInactiveInterval(5); %>  
in the JSP for testing but it seems erratic as to when Tomcat called sessionDestroyed().
To hewu, thanks for the points. But about kennethxu ?  He was a great help. I hope you implemented his last suggestions. He deserves points or at least a "thank you"
Avatar of hewu

ASKER

Yes. Thanks kennethxu, cheekycj ,debuchakrabarty ,objects and all of you for your great help. I appreciate your time.
This community keep me warm in my heart.Thanks again for your great experts!

   Wu
Glad to see you found a solution to work for you.  Great community effort guys :-)  Always a pleasure to participate/help with such great experts.

CJ
my pleasure to help, and thanks rrz :)