2016-12-17 3 views
0

私は本当に素敵なアプリケーションリスナーを以下のように登録しました。RequestHandledEventでHttpServletRequestを取得するSpring

@Component 
public class MyLogger implements ApplicationListener { 

    @Override 
    public void onApplicationEvent(ApplicationEvent event) { 
     // not doing anything here 
     // Check out the 'RequestHandledEvent' below though. 
    } 

    @EventListener(RequestHandledEvent.class) 
    public void onApplicationEvent(RequestHandledEvent event) { 
     // I'd like to get the HttpServletRequest that was just handled. 
     // Furthermore, I'd really like to get the userPrincipal that was 
     // on the request, so that I can know made the request 

     // it seems I can do this 
     // but the principal seems to already have been cleared. 
     // is there a more straightforward way to get the request? 
     HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); 
    } 

} 

私は

event.getRequest() 

ような何かを行うことができるはずような気がします。しかし、私はそうする成功した方法を発見していません。

かいつまんで、私はいくつかのロギングを行うことができるように、私はなど、ONE私が入って来たリクエストで取得することができます私のアプリケーションでPLACE、及びその要求にあった元本のようにたいと思います

多分別のアプリケーションイベントを見なければならないでしょうか?

答えて

2

あなたが好きなサーブレットフィルタを登録することで、適切なセキュリティプリンシパルで要求を取得することができます:あなたは@Order注釈を使用してフィルタクラスに注釈を付けたり、このようにフィルタを登録するか、フィルタチェインにfitersの順序を制御するには

@Component 
public static class RequestLoggingFilter extends OncePerRequestFilter { 

    @Override 
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { 
     final Principal userPrincipal = request.getUserPrincipal(); 
     // ...do what you want with principal and request info here 
     filterChain.doFilter(request, response); 
    } 
} 

@Bean 
public FilterRegistrationBean filterRegistrationBean() { 
    FilterRegistrationBean registrationBean = new FilterRegistrationBean(); 
    RequestLoggingFilter filter = new RequestLoggingFilter(); 
    registrationBean.setFilter(flter); 
    registrationBean.setOrder(Ordered.LOWEST_PRECEDENCE); 
    return registrationBean; 
} 
+0

応答がクライアントに返される前に、このフィルタが要求を処理する最後のものであることを確認するにはどうすればよいですか。 ご注文の設定はありますか? – Jeff

+1

フィルターの注文に関する情報を追加しました。 –

+0

よろしいですか。これはかなりうまくいくようです。問題は、Spring Securityのチェーンで問題が発生した場合(この例では悪いトークンが渡された場合)、このフィルタはヒットしません。 私は、これらのワークフローをすべて処理できるように単一の場所を見つけようとしています。ログを記録できるアプリケーションの単一の終了点を見つけることができます。 – Jeff

関連する問題