View Javadoc
1   /*
2    * Copyright 2002-2014 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.web.servlet.mvc.method.annotation;
18  
19  import javax.servlet.http.HttpServletResponse;
20  
21  import org.springframework.core.MethodParameter;
22  import org.springframework.http.HttpHeaders;
23  import org.springframework.http.server.ServletServerHttpResponse;
24  import org.springframework.util.Assert;
25  import org.springframework.web.context.request.NativeWebRequest;
26  import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
27  import org.springframework.web.method.support.ModelAndViewContainer;
28  
29  /**
30   * Handles {@link HttpHeaders} return values.
31   *
32   * @author Stephane Nicoll
33   * @since 4.0.1
34   */
35  public class HttpHeadersReturnValueHandler implements HandlerMethodReturnValueHandler {
36  
37  	@Override
38  	public boolean supportsReturnType(MethodParameter returnType) {
39  		return HttpHeaders.class.isAssignableFrom(returnType.getParameterType());
40  	}
41  
42  	@Override
43  	@SuppressWarnings("resource")
44  	public void handleReturnValue(Object returnValue, MethodParameter returnType,
45  			ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
46  
47  		mavContainer.setRequestHandled(true);
48  
49  		Assert.isInstanceOf(HttpHeaders.class, returnValue);
50  		HttpHeaders headers = (HttpHeaders) returnValue;
51  
52  		if (!headers.isEmpty()) {
53  			HttpServletResponse servletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
54  			ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(servletResponse);
55  			outputMessage.getHeaders().putAll(headers);
56  			outputMessage.getBody(); // flush headers
57  		}
58  	}
59  
60  }