Releases: cookie-meringue/rest_interceptor
v1.0.3
v1.0.2
v1.0.1
v1.0
v0.2
v0.1
Implement RestInterceptor with RestfulPattern for Handling Preflight and Request Matching
Description:
Implement a RestInterceptor that works with RestfulPattern, which stores URI and HTTP methods. The RestInterceptor should handle preflight requests and match incoming requests against the patterns in the RestfulPattern list.
1. RestfulPattern
- This will store a list of URI patterns and corresponding HTTP methods.
2. RestInterceptor
Abstract class RestInterceptor, which is an implementation of HandlerInterceptor.
RestInterceptor is a class created to solve the shortcomings of HandlerInterceptor, which is applied based on URI and must be set separately for CORS requests.
RestInterceptor implements the preHandle() method using Template Method Pattern.
The basic logic of preHandle() is implemented as final in RestInterceptor, and the actual preHandle() logic is implemented by implementing doInternal() in a child class.
The preHandle() of RestInterceptor, which is a Method Template, always returns true for two requests.
- Preflight requests (CORS).
- Do not match any of the
RestfulPatternentries in the list.
After checking the two requests above, doInternal() is called to perform the actual preHandle() logic.
3. RestInterceptorRegistration
This is the Restful version of InterceptorRegistration in org.springframework.web.servlet.config.annotation.
Since it uses RestfulPattern, it provides all the functions of InterceptorRegistration except the following functions.
addPathPatterns()excludePathPatterns()
4. RestInterceptorRegistry
This is an adapter for adding RestInterceptor to InterceptorRegistry.
Add RestInterceptors and create RestInterceptorRegistrations.
Once the configuration is complete, call the build() method to reflect RestInterceptorRegistrations to InterceptorRegistry.
The build() method will be deprecated in the future.
Usage
Assume we log GET /memos requests.
We do not log POST /memos .
1. Create Interceptor
@Slf4j
@Component
public class RestTestInterceptor extends RestInterceptor {
@Override
protected boolean doInternal(HttpServletRequest request, HttpServletResponse response, Object handler) {
log.info("doInternal");
return true;
}
}
2. Add Interceptor in the implementation configuration class of WebMvcConfigurer
@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
private final RestTestInterceptor testInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
RestInterceptorRegistry restInterceptorRegistry = new RestInterceptorRegistry(registry);
restInterceptorRegistry.addInterceptor(testInterceptor)
.addRestfulPatterns(RestfulPattern.of("/memos", HttpMethod.GET));
restInterceptorRegistry.build();
}
}