0

We're using Spring MVC (3.0.5) for an API we are building. However, we have discovered that the application does not always return a content-length in the response header. Why I haven't figured out as yet. We can not manually set the content-length in the controller (request.setContentLength(x)) because we only use a subset of the data we get with the controller in our Freemarker view. So basically what we need is to calculate and set the content-length after a view has been resolved/compiled and just before it is actually sent to client.

Are there any common ("good praxis") ways to do this? Or even "ugly" ways?

Skurpi
  • 1,000
  • 1
  • 12
  • 22

1 Answers1

2

Intercept your requests by implementing the HandlerInterceptor interface. The afterCompletion method runs after the view is resolved, so you should be able to set the value there, as that method's signature passes the HttpServletResponse. Configure thusly:

<!-- Configures Handler Interceptors -->    
<mvc:interceptors>
    <bean class="com.myapp.web.interceptor.MyInterceptor" />
</mvc:interceptors>

Here's some basic code:

@Component
public class MyInterceptor implements HandlerInterceptor {
}
atrain
  • 9,139
  • 1
  • 36
  • 40
  • Cool! Does it have access to the resolved view at this point? In order for me to calculate the content-length – Skurpi Sep 20 '11 at 07:12
  • I believe so, as the afterCompletion method runs after all handler and view processing has been completed. See http://stackoverflow.com/questions/5435351/determine-size-of-http-response, David's answer for how to get the size of the response. – atrain Sep 20 '11 at 13:13
  • Actually, this won't work because the interceptor method postHandle will be run before the view is resolved and sent, and afterCompletion will be run after the view is resolved and sent. There is nothing inbetween using this solution – Skurpi Jan 20 '12 at 13:04