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()
但我还没有找到成功的方法来做到这一点。
长话短说,我希望我的应用程序中有一个地方,我可以根据请求进来,请求的主体是这样,以便我可以做一些日志记录等。
我应该看看不同的应用程序事件吗?
@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注解注释你的过滤器类或类似这样的注册过滤器:
我该如何确保这个过滤器是最后一件东西,在响应被发送回客户端之前处理请求? 是否有订购配置,我可以阅读? – Jeff
添加了有关过滤器订购的信息。 –
好的。这似乎工作很好。问题是,如果Spring Security链中发生了一些事情(例如 - 坏的令牌被传入),这个过滤器不会被打中。 我试图找到能够处理所有这些工作流程的单点,并找到我可以登录的应用程序的单点退出。 – Jeff