tags:

views:

1826

answers:

3

I have a Spring Interceptor which attempts to add an HTTP header in the postHandle() method.

public void postHandle(HttpServletRequest req, HttpServletResponse resp, 
             Object obj1, ModelAndView mv)
  throws Exception {
  response.setHeader("SomeHeaderSet", "set");
  response.addHeader("SomeHeaderAdd", "added");
 }
}

However, neither header is added with either setHeader() or addHeader().

Is this even valid to do in the interceptor? I figured it WOULD be, but it ain't workin.

Regards, Dustin

A: 

Have you tried setting the headers in the preHandle method? If that doesn't work try writing a Filter for the container and set the headers in there instead.

Jonathan
Well, I can't do it in the preHandle method because the header I need to set is based on the servlet processing results, so it has to be done in the postHandle method.
Dustin
+1  A: 

Well, I figured it out...Kinda...

Turns out, same issue with Jetty and Tomcat (figured MAYBE it was a container issue). So...

Debugged to ensure that the response object contained the correct header value up until Spring returned back to the container. Result: The HttpServletResponse instance still had the correct header value.

I found in my code I was invoking response.setContentLength() BEFORE I was doing anything with the headers. If I comment it out, everything works fine.

So, the remaining mystery is, why does calling response.setContentLength() lock things down and not allow any headers to be modified? I didn't think the content body had anything to do with the other headers.

Dustin
A: 

I had a similar problem, it works when I have the following in the web.xml (haven't figured out why)

<filter>
  <filter-name>etagFilter</filter-name>
    <filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>etagFilter</filter-name>
  <servlet-name>myServlet</servlet-name>
</filter-mapping>
Kristian