Vivek Mohan
Vivek Mohan

Reputation: 8366

Request/response handling in javax.servlet.filter class

How to detect if it is a request/response the filter class is going to handle? Also I need to cancel the request to my servlet and want to create my own response and return it from dofilter method. Is there any possible way to do this?

Upvotes: 1

Views: 2751

Answers (2)

Vivek Mohan
Vivek Mohan

Reputation: 8366

I have mofied the response using response.getWriter().write("response data"); And avoided the response from passing to the servlet by removing that chain.doFilter();

Now, I am validating session variables(for authentication) from doFilter method. Since both requests and response are handling in same doFilter method, I think these session validation is happening 2 times (1.) while request happens & (2.) while reponse. But, how to find what doFilter is currently handling (request /response)? So i can make session validation happen only at request time.

Upvotes: 0

ziesemer
ziesemer

Reputation: 28707

Each filter can affect none, one, or both of the request and response. It all depends upon if you do anything before and/or after calling chain.doFilter(...) - and if you pass in a wrapped request and/or response.

If you need to create your own response within the filter, simply don't call chain.doFilter(...) and provide your own response from the filter.

Please refer to the Filter.doFilter Javadocs, including:

A typical implementation of this method would follow the following pattern:- 1. Examine the request 2. Optionally wrap the request object with a custom implementation to filter content or headers for input filtering 3. Optionally wrap the response object with a custom implementation to filter content or headers for output filtering 4. a) Either invoke the next entity in the chain using the FilterChain object (chain.doFilter()), 4. b) or not pass on the request/response pair to the next entity in the filter chain to block the request processing 5. Directly set headers on the response after invocation of the next entity in the filter chain.

Upvotes: 2

Related Questions