OncePerRequestFilter class abstract
A specialized Filter that guarantees execution only once per request.
This is useful for filters that perform actions that should not be repeated if the request passes through the filter multiple times due to nested dispatches, forwards, or filter re-registration.
Instead of overriding doFilter, subclasses should implement doFilterInternal. This method contains the actual filter logic. The base class ensures that this method is called at most once per request.
Lifecycle
- When doFilter is called, it checks if the filter has already been applied
to the request (via the
_FILTER_APPLIEDmarker). - If it has been applied, the filter skips execution and delegates to the next element in the chain.
- If not, the filter marks the request as "applied", calls doFilterInternal, and cleans up afterwards.
Use Cases
- Security filters (e.g., authentication/authorization)
- Logging filters that should only log once
- CORS or header-setting filters
Example
class SecurityFilter extends OncePerRequestFilter {
@override
Future<void> doFilterInternal(ServerHttpRequest request, ServerHttpResponse response, FilterChain chain) async {
final token = request.getHeaders().get("Authorization");
if (token == null) {
response.setStatus(HttpStatus.UNAUTHORIZED);
return;
}
await chain.next(request, response);
}
}
- Implemented types
- Implementers
Constructors
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
doFilter(
ServerHttpRequest request, ServerHttpResponse response, FilterChain chain) → Future< void> -
Called for each HTTP request and response.
override
-
doFilterInternal(
ServerHttpRequest request, ServerHttpResponse response, FilterChain chain) → Future< void> - Subclasses implement this instead of doFilter to define the actual filtering logic.
-
equalizedProperties(
) → List< Object?> -
Mixin-style contract for value-based equality,
hashCode, andtoString.inherited -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited