This question already has an answer here:
I have a web application and for that I want to capture the IP address of the clients who are accessing my website so that I can know what region is the most accessing the application. I am using Java EE
in my application.
Probably there is some solution if we talk about header and when request
is sent from the end-user.
The request object is passed as a Java argument to the servlet method generated from your JSP. The argument's name is ... wait for it ...
request
.So you should be able to refer to it in a scriptlet embedded in your JSP; e.g.
It is debatable whether you should be doing this kind of thing in a JSP. It is generally accepted as "best practice" that JSPs should only be used for formatting output. The business logic of a webapp should be in a controller servlet that then finally forwards to the JSP servlet to generate the HTML (or whatever).
If you are going to put business logic into a JSP, scriptlets tend to be difficult to maintain ... though if you are just going to display the IP address, that shouldn't be a concern. (The preferred approach from an engineering perspective is to use tags and JSP expression language.)
Finally, there is no guarantee that the IP address returned by
getRemoteAddr()
will be the actual client IP address. It could be the address of a proxy, or even a complete fabrication.Use method getRemoteAddr() from interface ServletRequest or methods getHeaders() form interface HttpServletRequest:
There's one caution for using the method getRemoteAddr:
Sure you can use the method and in general case you will get IP of client. However, the method is useless if an user is behind a proxy. In this case you'll get the proxy server's IP address and not the client. But the proxy may include the requesting client IP in a special
HTTP
header. So to retrieve real-client-IP call methodgetHeader("X-Forwarded-For")
.An example usage in JSP:
Use set value of IP address in session using JSTL:
And then get this value from the session in a convenient place.
In JSP you can use
<c:out value="${sessionScope.userIp}" />
or in servlet assession.getAttribute('userIp');
Please read docs:
Along with the above said answers (by Andrey and Stephen) do use some
analytics
tool also. It will give you a bigger picture of the traffic coming to your website. One such example is Google Analytics.