ContentNegotiationStrategy
是Spring Web
的策略接口,所定义的策略对象用于从请求对象中的各种信息判断该请求的MediaType
。
源代码
源代码版本 : Spring Security Config 5.1.4.RELEASE
package org.springframework.web.accept;
import java.util.Collections;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.context.request.NativeWebRequest;
/**
* A strategy for resolving the requested media types for a request.
*
* @author Rossen Stoyanchev
* @since 3.2
*/
@FunctionalInterface
public interface ContentNegotiationStrategy {
/**
* A singleton list with MediaType#ALL that is returned from
* #resolveMediaTypes when no specific media types are requested.
* @since 5.0.5
*/
List<MediaType> MEDIA_TYPE_ALL_LIST = Collections.singletonList(MediaType.ALL);
/**
* Resolve the given request to a list of media types. The returned list is
* ordered by specificity first and by quality parameter second.
* @param webRequest the current request
* @return the requested media types, or #MEDIA_TYPE_ALL_LIST if none
* were requested.
* @throws HttpMediaTypeNotAcceptableException if the requested media
* types cannot be parsed
*/
List<MediaType> resolveMediaTypes(NativeWebRequest webRequest)
throws HttpMediaTypeNotAcceptableException;
}
由以上接口源代码可以看出,ContentNegotiationStrategy
主要定义了一个方法List<MediaType> resolveMediaTypes(NativeWebRequest webRequest)
。该方法接受一个参数NativeWebRequest webRequest
,表示请求对象,该方法的实现要分析该请求对象获得他的MediaType
列表。
实现类
接口ContentNegotiationStrategy
有如下实现类 :
FixedContentNegotiationStrategy
该策略对象创建时固定了一组
MediaType
,不管请求对象是什么,都返回这组MediaType
HeaderContentNegotiationStrategy
该策略对象分析请求头部
Accept
得出该请求的一组MediaType
,如果请求头部Accept
未设置,返回的MediaType
只包含*/*
。
ParameterContentNegotiationStrategy
根据一个查询参数(
query parameter
)判断请求的
MediaType,该查询参数缺省使用
format`。
PathExtensionContentNegotiationStrategy
根据请求
URL
路径中所请求的文件资源的扩展名部分判断请求的MediaType
。
ServletPathExtensionContentNegotiationStrategy
扩展自
PathExtensionContentNegotiationStrategy
,将使用ServletContext#getMimeType(String)
方法判断请求MediaType
的能力也包含进来
ContentNegotiationManager
一个
ContentNegotiationStrategy
容器,同时也是一个MediaTypeFileExtensionResolver
容器。自身同时实现了这两个接口。调用者对该策略对象所调用的接口功能会并未委托给所包含的ContentNegotiationStrategy
/MediaTypeFileExtensionResolver
计算得到。