4

シンプルなフォームからユーザー データを取得します。対応するバッキング Bean のアクション メソッドでデータを処理する場合、現在、次の方法でユーザーの IP アドレスを取得しています。

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

フックする必要のない別の方法、より「JSF」な方法はありHttpServletRequestますか? javax.servlet.*で使用する必要があるのは良いデザインではないことを何度も読みました@ManagedBeanが、他に何も見つかりませんでした。

4

1 に答える 1

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();
}

X-Forwarded-Forheader はカンマ区切りの文字列を表し、独自のコードではそれが考慮されていないことに注意してください。

于 2013-03-28T10:46:11.810 に答える