I have implemented a Filter like this but this triggers only when the request is coming in. I would like to intercept the response on its way out i.e. when the response is returned from controller.
I know about Spring Interceptors which give you the functionality to handle the request before and after it hits the controller. I would like to do something like that.
public class ServiceSessionManagementInterceptor implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
Map<String, String[]> maps = request.getParameterMap();
System.out.println("test");
chain.doFilter(request, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks.
Interceptors share a common API for the server and the client side. Whereas filters are primarily intended to manipulate request and response parameters like HTTP headers, URIs and/or HTTP methods, interceptors are intended to manipulate entities, via manipulating entity input/output streams.
doFilter. Causes the next filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked. Parameters: request - the request to pass along the chain.
Interceptors will only execute after Filters. Fine-grained pre-processing tasks are suitable for HandlerInterceptors (authorization checks, etc.) Content handling related or generic flows are well-suited for Filters (such as multipart forms, zip compression, image handling, logging requests, authentication etc.)
The doFilter()
is where magic happens. Whatever you put before it will be executed before the servlet and everything you put after it will be executed after the servlet service()
method returns (including a forward/include, etc.).
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("before");
chain.doFilter(request, response);
System.out.println("after");
}
This way you could wrap the ServletRequest
and ServletResponse
objects with your own implementations to add functionality, ex: compression.
Note that a Spring Interceptor
is called before and after the handler method gets executed. A servlet Filter
gets executed before and after a Servlet
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With