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计算得到。
解析SpringWeb的ContentNegotiationStrategy
本文详细介绍了SpringWeb框架中ContentNegotiationStrategy接口及其实现类,包括FixedContentNegotiationStrategy、HeaderContentNegotiationStrategy等,探讨了它们如何处理请求的MediaType,为理解SpringWeb的内容协商策略提供了深入的视角。
706

被折叠的 条评论
为什么被折叠?



