Add JSONP support for MappingJackson2MessageConverter

Issue: SPR-9899
This commit is contained in:
Rossen Stoyanchev
2014-05-19 22:10:51 -04:00
parent 05e96ee448
commit 1338d46a6e
8 changed files with 311 additions and 40 deletions

View File

@@ -0,0 +1,86 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.method.annotation;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
/**
* A convenient base class for a {@code ResponseBodyInterceptor} to instruct the
* {@link org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
* MappingJackson2HttpMessageConverter} to serialize with JSONP formatting.
*
* <p>Sub-classes must specify the query parameter name(s) to check for the name
* of the JSONP callback function.
*
* <p>Sub-classes are likely to be annotated with the {@code @ControllerAdvice}
* annotation and auto-detected or otherwise must be registered directly with the
* {@code RequestMappingHandlerAdapter} and {@code ExceptionHandlerExceptionResolver}.
*
* @author Rossen Stoyanchev
* @since 4.1
*/
public abstract class AbstractJsonpResponseBodyInterceptor extends AbstractMappingJacksonResponseBodyInterceptor {
private final String[] jsonpQueryParamNames;
protected AbstractJsonpResponseBodyInterceptor(Collection<String> queryParamNames) {
Assert.isTrue(!CollectionUtils.isEmpty(queryParamNames), "At least one query param name is required");
this.jsonpQueryParamNames = queryParamNames.toArray(new String[queryParamNames.size()]);
}
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
for (String name : this.jsonpQueryParamNames) {
String value = servletRequest.getParameter(name);
if (value != null) {
MediaType contentTypeToUse = getContentType(contentType, request, response);
response.getHeaders().setContentType(contentTypeToUse);
bodyContainer.setJsonpFunction(value);
return;
}
}
}
/**
* Return the content type to set the response to.
* This implementation always returns "application/javascript".
* @param contentType the content type selected through content negotiation
* @param request the current request
* @param response the current response
* @return the content type to set the response to
*/
protected MediaType getContentType(MediaType contentType, ServerHttpRequest request, ServerHttpResponse response) {
return new MediaType("application", "javascript");
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.method.annotation;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
/**
* A convenient base class for {@code ResponseBodyInterceptor} implementations
* that customize the response before JSON serialization with
* {@link org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
* MappingJackson2HttpMessageConverter}.
*
* @author Rossen Stoyanchev
* @since 4.1
*/
public abstract class AbstractMappingJacksonResponseBodyInterceptor implements ResponseBodyInterceptor {
protected AbstractMappingJacksonResponseBodyInterceptor() {
}
@SuppressWarnings("unchecked")
@Override
public final <T> T beforeBodyWrite(T body, MediaType contentType,
Class<? extends HttpMessageConverter<T>> converterType,
MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
if (!MappingJackson2HttpMessageConverter.class.equals(converterType)) {
return body;
}
MappingJacksonValue container = getOrCreateContainer(body);
beforeBodyWriteInternal(container, contentType, returnType, request, response);
return (T) container;
}
/**
* Wrap the body in a {@link MappingJacksonValue} value container (for providing
* additional serialization instructions) or simply cast it if already wrapped.
*/
protected MappingJacksonValue getOrCreateContainer(Object body) {
return (body instanceof MappingJacksonValue) ? (MappingJacksonValue) body : new MappingJacksonValue(body);
}
/**
* Invoked only if the converter type is {@code MappingJackson2HttpMessageConverter}.
*/
protected abstract void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response);
}

View File

@@ -19,42 +19,40 @@ package org.springframework.web.servlet.mvc.method.annotation;
import com.fasterxml.jackson.annotation.JsonView;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.Assert;
/**
* A {@code ResponseBodyInterceptor} implementation that adds support for the
* Jackson {@code @JsonView} annotation on a Spring MVC {@code @RequestMapping}
* or {@code @ExceptionHandler} method.
* A {@code ResponseBodyInterceptor} implementation that adds support for
* Jackson's {@code @JsonView} annotation declared on a Spring MVC
* {@code @RequestMapping} or {@code @ExceptionHandler} method. The serialization
* view specified in the annotation will be passed in to the
* {@code MappingJackson2HttpMessageConverter} which will then use it to
* serialize the response body with.
*
* @author Rossen Stoyanchev
* @since 4.1
*
* @see com.fasterxml.jackson.databind.ObjectMapper#writerWithView(Class)
*/
public class JsonViewResponseBodyInterceptor implements ResponseBodyInterceptor {
public class JsonViewResponseBodyInterceptor extends AbstractMappingJacksonResponseBodyInterceptor {
@Override
@SuppressWarnings("unchecked")
public <T> T beforeBodyWrite(T body, MediaType contentType, Class<? extends HttpMessageConverter<T>> converterType,
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
if (!MappingJackson2HttpMessageConverter.class.equals(converterType)) {
return body;
}
JsonView annotation = returnType.getMethodAnnotation(JsonView.class);
if (annotation == null) {
return body;
return;
}
Assert.isTrue(annotation.value().length != 0,
"Expected at least one serialization view class in JsonView annotation on " + returnType);
return (T) new MappingJacksonValue(body, annotation.value()[0]);
bodyContainer.setSerializationView(annotation.value()[0]);
}
}