I could not get the correct difference between filters and interceptors. So Please explain me the exact use of filters and interceptors in java based web application with some sample snippet.
An HTTP interceptor intercepts all received HTTP requests and outbound HTTP responses. Integration Server makes the raw HTTP request and response, including the HTTP header information, accessible to the HTTP interceptor.
Filter is related to the Servlet API and HandlerIntercepter is a Spring specific concept. Interceptors will only execute after Filters. Fine-grained pre-processing tasks are suitable for HandlerInterceptors (authorization checks, etc.)
Performs security handling of HTTP resources via a filter implementation.
Spring Interceptor are used to intercept client requests and process them. Sometimes we want to intercept the HTTP Request and do some processing before handing it over to the controller handler methods.
Filters are used in Web Applications to perform some actions on the request or the response, before it reaches or after it leaves the actual action handler on the sever ( which might be a Servlet, a REST service, a JSF Managed Bean, etc.). By using filters you can for example check to see if certain requests are authorised for the logged in user, and you can actually cancel the request and return a response to the client, without allowing the request to reach the actual action handler.
If you have more than one filter you will have to chain them.
Interceptors are acting on class methods. It allows you to do some additional processing while invoking a method of an object, without the need to alter the method body. This can be very useful when:
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