spring-framework: New OncePerRequestFilter behavior breaks RequestContextFilter on Jetty after sendError

After the change to OncePerRequestFilter in #22989, when using a RequestContextFilter, the request context will no longer be available after sendError(...) completes in Jetty. This means that the usage of any @Scope("request") beans in places like the afterCompletion in interceptors or on the return path of filters will not work, nor will more general usage of RequestContextHolder.getRequestAttributes() work.

The problem is that the change in OncePerRequestFilter causes the filter to be processed again, even though it is a OncePerRequestFilter. And the RequestContextFilter is not designed to be nested. The finally block clears all request attributes, even when attributes were set before the filter started.

I’m not really sure what the best solution would be. Maybe introduce a OncePerRequestFilter.shouldNotFilterOnNestedErrorDispatch() or something. Or maybe make RequestContextFilter restore the previous request context, instead of clearing everything (it seems like FrameworkServlet does this too)? Or both.

Affected version: 5.1.8

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 15 (12 by maintainers)

Commits related to this issue

Most upvoted comments

The new doFilterNestedErrorDispatch method is now in while the change from #22989 that caused the regression has been removed.

@rwinch this means there is a need for a follow-up for https://github.com/spring-projects/spring-session/issues/1308 to ensure affected filters implement the new method.

By the way I checked Tomcat and Jetty behavior in case of an error, regarding double wrapping:

  • For Tomcat, doFilterInternal is called once for REQUEST and once for ERROR. This matches long existing behavior since the ERROR dispatch is a completely separate filter chain invocation. No double wrapping occurs.
  • For Jetty, doFilterInternal is called for REQUEST, and doFilterNestedErrorDispatch is called for ERROR, allowing wrapping in case of a nested ERROR dispatch.