Clientrequestfilter vs Containerrequestfilter

2019-03-25 20:53发布

问题:

I knew filters are used to handle the request and can do things with http header and httpmethods, but am confused with

What is the difference between clientrequestfilter and containerrequestfilter? Inwhich scenario we have to use clientrequestfilter and containerrequestfilter?

I tried with this website but not any details about this.

Please help me to understand this.

回答1:

There are two side to a REST interaction, the client and the server. Jersey/JAX-RS-2 has both a Client API and the "main" Server side API. When working with the Client API, we could use the ClientRequestFilter, and when using the Server Side API, we would use the ContainerRequestFilter. There's no possibility to mix and match these, they should strictly be used with the appropriate side of the interaction.

A ContainerRequestFilter (Server Side) example would be to do some authorization/authentication, which a pretty common use case for server side filter. The filter will be invoked before reaching any of your resources

Client --->  Internet ---> Server ---> Filter ---> Resource

A ClientRequestFilter (Client Side) example would be implement some client side cache (sort of mocking a browser cache). Or a a case (which already has been implemented) is a filter to encode a user name and password for BASIC authentication. Before the request actually gets sent to the server, the client filter will get invoked.

Client ---> Filter ---> Internet ---> Server ---> Resource

There are also XxxResponseFilters that follow the following flow

Resource ---> ContainerResponseFilter ---> Server ---> Internet ---> Client

Server ---> Internet ---> ClientResponseFilter ---> Client