views:

39

answers:

1

I have a servlet that does a request dispatcher include of another servlet.

The included servlet sets headers that I would like to read in the including servlet. So I pass in a custom HTTPResponse object in the include() method which captures all feedback activity from the servlet.

The problem is that the headers are not being set in my custom response. I've run in debug and examined what looks like Tomcat wrapping my custom response object with its own response object. The setHeader calls go to this wrapping class and never propagate to my custom response object.

I imagine Tomcat does this to protect the client from headers being set in the wrong place. The funny thing is that the same approach works the way I'd expect in Jetty.

It's been a while since I've done Servlets seriously so I'm struggling a bit here. I'm trying to figure out how to read the response headers from a servlet that's invoked via dispatcher.include().

+3  A: 

From the Servlet specifications section SRV.8.3:

The include method of the RequestDispatcher interface may be called at any time. The target servlet of the include method has access to all aspects of the request object, but its use of the response object is more limited.

It can only write information to the ServletOutputStream or Writer of the response object and commit a response by writing content past the end of the response buffer, or by explicitly calling the flushBuffer method of the ServletResponse interface.

It cannot set headers or call any method that affects the headers of the response. Any attempt to do so must be ignored.

How about setting your values for the calling servlet in request scope, with request.setAttribute(...) and then reading it from there once you return? Could that work?

dpb
In other words, Jetty is doing it wrong.
BalusC
Thank you for clarifying the behavior for me. You know I thought about using request.setAttribute(). That would work and I was reserving that as plan B as it's not optimal in the sense of D.R.Y. I need access to the content-type and content length to propagate to the including servlet. Using request attributes forces redundancy. Still, the included servlet *is* in need of refactoring. Thanks again!
Cliff
If I converted my *including* servlet to a Filter would that work? I mean is it a spec violation to write headers in a servlet invoked by a Filter?
Cliff