使用JSF API获取用户IP地址,而无需Servlet API

Med*_*Med 4 ip-address jsf-2

我通过一个简单的表单获得了一些用户数据.在处理相应的backing bean的action方法中的数据时,我正在以这种方式获取用户的IP地址:

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

还有另一种方式,一种更"JSF"的方式,我不需要挂钩HttpServletRequest?我多次读过,不得不javax.servlet.*@ManagedBean一个好的设计中使用,但我找不到别的东西.

Bal*_*usC 16

不,没有.在ExternalContext不具有委托给方法ServletRequest#getRemoteAddr().

最好的办法是用一种方法将它隐藏起来.JSF实用程序库OmniFacesFaces实用程序类中具有许多其他有用的方法:Faces#getRemoteAddr()这也是将转发的地址考虑在内.

源代码是在这里:

/**
 * 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's 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's a comma separated string: client,proxy1,proxy2,...
    }

    return getRequest().getRemoteAddr();
}
Run Code Online (Sandbox Code Playgroud)

请注意,X-Forwarded-For标头代表一个逗号分隔的字符串,并且您自己的代码没有考虑到这一点.