pradeep
pradeep

Reputation: 295

Filters vs interceptors in web application

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.

Upvotes: 13

Views: 7992

Answers (1)

iullianr
iullianr

Reputation: 1284

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:

  • you do not have access to the method's body
  • the processing is something that is repeated for a specific type of methods and you do not want to put that extra code everywhere (for example logging the input parameters and the output result in order to track the execution or check the security constraints on a specific method, if you have defined some).

Upvotes: 14

Related Questions