在RequestHandledEvent Spring

时间:2016-12-17 01:08:35

标签: spring spring-boot spring-aop

我有一个非常好的应用程序监听器,如下所示。

@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,我可以得到进来的请求,以及该请求的主体,以便我可以做一些记录等。

我应该看一下不同的申请活动吗?

1 个答案:

答案 0 :(得分:2)

您可以通过注册servlet过滤器来获取具有适当安全主体的请求:

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

要控制过滤器链中fiters的顺序,您可以使用@Order注释来注释过滤器类,或者像这样注册过滤器:

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