001/* 002 * Copyright 2002-2014 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.servlet.mvc.method.annotation; 018 019import org.springframework.core.MethodParameter; 020import org.springframework.http.MediaType; 021import org.springframework.http.converter.HttpMessageConverter; 022import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter; 023import org.springframework.http.converter.json.MappingJacksonValue; 024import org.springframework.http.server.ServerHttpRequest; 025import org.springframework.http.server.ServerHttpResponse; 026 027/** 028 * A convenient base class for {@code ResponseBodyAdvice} implementations 029 * that customize the response before JSON serialization with 030 * {@link AbstractJackson2HttpMessageConverter}'s concrete subclasses. 031 * 032 * @author Rossen Stoyanchev 033 * @author Sebastien Deleuze 034 * @since 4.1 035 */ 036public abstract class AbstractMappingJacksonResponseBodyAdvice implements ResponseBodyAdvice<Object> { 037 038 @Override 039 public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { 040 return AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType); 041 } 042 043 @Override 044 public final Object beforeBodyWrite(Object body, MethodParameter returnType, 045 MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType, 046 ServerHttpRequest request, ServerHttpResponse response) { 047 048 MappingJacksonValue container = getOrCreateContainer(body); 049 beforeBodyWriteInternal(container, contentType, returnType, request, response); 050 return container; 051 } 052 053 /** 054 * Wrap the body in a {@link MappingJacksonValue} value container (for providing 055 * additional serialization instructions) or simply cast it if already wrapped. 056 */ 057 protected MappingJacksonValue getOrCreateContainer(Object body) { 058 return (body instanceof MappingJacksonValue ? (MappingJacksonValue) body : new MappingJacksonValue(body)); 059 } 060 061 /** 062 * Invoked only if the converter type is {@code MappingJackson2HttpMessageConverter}. 063 */ 064 protected abstract void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType, 065 MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response); 066 067}