Get the user's IP address using the JSF API without the need for a Servlet API

I get some user data through a simple form. When you work with data in the corresponding bean support method, I currently get the user's IP address this way:

HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); String ipAddress = request.getHeader( "X-FORWARDED-FOR" ); if ( ipAddress == null ) { ipAddress = request.getRemoteAddr(); } 

Is there any other way, more "JSF", where I do not need to cling to the HttpServletRequest ? I read many times that using javax.servlet.* In @ManagedBean not a good design, but I could not find anything.

+4
source share
1 answer

No no. ExternalContext does not have a method that delegates ServletRequest#getRemoteAddr() .

It’s best to hide it in the utlity method. The JSF utility OmniFaces has, among many other useful methods, this method in Faces : Faces#getRemoteAddr() , which also takes into account the redirected address.

source code is here:

 /** * Returns the Internet Protocol (IP) address of the client that sent the request. This will first check the * <code>X-Forwarded-For</code> request header and if it present, then return its first IP address, else just * return {@link HttpServletRequest#getRemoteAddr()} unmodified. * @return The IP address of the client. * @see HttpServletRequest#getRemoteAddr() * @since 1.2 */ public static String getRemoteAddr() { String forwardedFor = getRequestHeader("X-Forwarded-For"); if (!Utils.isEmpty(forwardedFor)) { return forwardedFor.split("\\s*,\\s*", 2)[0]; // It a comma separated string: client,proxy1,proxy2,... } return getRequest().getRemoteAddr(); } 

Note that the X-Forwarded-For header is a delimited string and that your own code does not take this into account.

+15
source

All Articles