Wednesday, June 9, 2010

Getting client information in Java ServerFaces

I always log client information in JSF applications in debug mode. I use the following code in a managed bean to retrieve the IP-address, hostname and HTTP-headers from the browser.

// Get the request-object.
HttpServletRequest request = (HttpServletRequest)
(FacesContext.getCurrentInstance().
getExternalContext().getRequest());

// Get the header attributes. Use them to retrieve the actual
// values.
request.getHeaderNames();

// Get the IP-address of the client.
request.getRemoteAddr();

// Get the hostname of the client.
request.getRemoteHost();

3 comments:

  1. Sale Japani.... Galat Hai Be ...:P

    ReplyDelete
  2. If I want private IP? for example: 192.168.0.3. How I can do that
    Thanks

    ReplyDelete
    Replies
    1. The IP is retrieved from the established TCP connection. Unless the connection is made with a private IP, which means the client is on the same private network, it is not possible to retrieve the private IP.

      Delete