Spring Webflux --accept
RequestedContentTypeResolver策略和實現(xiàn)來解析給定請求的請求內(nèi)容類型贴见。
接口
RequestedContentTypeResolver
為ServerWebExchange解決請求的媒體類型的策略狱意。
public interface RequestedContentTypeResolver {
/**
* Resolve the given request to a list of requested media types. The returned
* list is ordered by specificity first and by quality parameter second.
* @param exchange the current exchange
* @return the requested media types or an empty list
* @throws NotAcceptableStatusException if the requested media type is invalid
*/
List<MediaType> resolveMediaTypes(ServerWebExchange exchange);
}
將給定的請求解析為請求的媒體類型列表。返回的列表首先按特異性排序筋遭,然后按質(zhì)量參數(shù)排序。
類
org.springframework.web.reactive.accept.FixedContentTypeResolver
解析器始終解析為媒體類型的固定列表暴拄。這可以用作“最后一行”策略漓滔,當客戶端沒有請求任何媒體類型時提供回調(diào)
public class FixedContentTypeResolver implements RequestedContentTypeResolver {
private static final Log logger = LogFactory.getLog(FixedContentTypeResolver.class);
private final List<MediaType> mediaTypes;
/**
* 具有單個默認MediaType的構造函數(shù)。.
*/
public FixedContentTypeResolver(MediaType mediaType) {
this(Collections.singletonList(mediaType));
}
/**
* 使用默認的MediaType排序列表的構造函數(shù)返回用于支持各種內(nèi)容類型的應用程序乖篷。
如果目標不存在响驴,并且不支持任何其他默認媒體類型,請考慮在最后附加MediaType.ALL那伐。
*/
public FixedContentTypeResolver(List<MediaType> mediaTypes) {
this.mediaTypes = Collections.unmodifiableList(mediaTypes);
}
/**
* 返回配置的媒體類型列表踏施。
*/
public List<MediaType> getContentTypes() {
return this.mediaTypes;
}
@Override
public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) {
if (logger.isDebugEnabled()) {
logger.debug("Requested media types: " + this.mediaTypes);
}
return this.mediaTypes;
}
}
org.springframework.web.reactive.accept.HeaderContentTypeResolver
解析器查看請求的“Accept”標頭。
public class HeaderContentTypeResolver implements RequestedContentTypeResolver {
@Override
public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
try {
List<MediaType> mediaTypes = exchange.getRequest().getHeaders().getAccept();
MediaType.sortBySpecificityAndQuality(mediaTypes);
return mediaTypes;
}
catch (InvalidMediaTypeException ex) {
String value = exchange.getRequest().getHeaders().getFirst("Accept");
throw new NotAcceptableStatusException(
"Could not parse 'Accept' header [" + value + "]: " + ex.getMessage());
}
}
}
org.springframework.web.reactive.accept.ParameterContentTypeResolver
解析查詢參數(shù)并使用它查找匹配的MediaType的解析器罕邀。查找鍵可以注冊畅形,也可以作為一個后備的MediaTypeFactory執(zhí)行查找。
public class ParameterContentTypeResolver implements RequestedContentTypeResolver {
/** Primary lookup for media types by key (e.g. "json" -> "application/json") */
private final Map<String, MediaType> mediaTypes = new ConcurrentHashMap<>(64);
private String parameterName = "format";
public ParameterContentTypeResolver(Map<String, MediaType> mediaTypes) {
mediaTypes.forEach((key, value) -> this.mediaTypes.put(formatKey(key), value));
}
private static String formatKey(String key) {
return key.toLowerCase(Locale.ENGLISH);
}
/**
* Set the name of the parameter to use to determine requested media types.
* <p>By default this is set to {@literal "format"}.
*/
public void setParameterName(String parameterName) {
Assert.notNull(parameterName, "'parameterName' is required");
this.parameterName = parameterName;
}
public String getParameterName() {
return this.parameterName;
}
@Override
public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
String key = exchange.getRequest().getQueryParams().getFirst(getParameterName());
if (!StringUtils.hasText(key)) {
return Collections.emptyList();
}
key = formatKey(key);
MediaType match = this.mediaTypes.get(key);
if (match == null) {
match = MediaTypeFactory.getMediaType("filename." + key)
.orElseThrow(() -> {
List<MediaType> supported = new ArrayList<>(this.mediaTypes.values());
return new NotAcceptableStatusException(supported);
});
}
this.mediaTypes.putIfAbsent(key, match);
return Collections.singletonList(match);
}
org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder
Builder的復合RequestedContentTypeResolver代表其他解析器實現(xiàn)一個不同的策略來確定請求的內(nèi)容類型,例如Accept標頭,查詢參數(shù),或其他诉探。
使用生成器方法在所需的順序中添加解析器日熬。對于給定的請求,他首先解析返回一個非空的列表肾胯,并且不包含只是MediaType竖席。將使用耘纱。
默認情況下,如果沒有顯式解析器配置,構建器將添加HeaderContentTypeResolver。
public class RequestedContentTypeResolverBuilder {
private final List<Supplier<RequestedContentTypeResolver>> candidates = new ArrayList<>();
/**
* Add a resolver to get the requested content type from a query parameter.
* By default the query parameter name is {@code "format"}.
*/
public ParameterResolverConfigurer parameterResolver() {
ParameterResolverConfigurer parameterBuilder = new ParameterResolverConfigurer();
this.candidates.add(parameterBuilder::createResolver);
return parameterBuilder;
}
/**
* Add resolver to get the requested content type from the
* {@literal "Accept"} header.
*/
public void headerResolver() {
this.candidates.add(HeaderContentTypeResolver::new);
}
/**
* Add resolver that returns a fixed set of media types.
* @param mediaTypes the media types to use
*/
public void fixedResolver(MediaType... mediaTypes) {
this.candidates.add(() -> new FixedContentTypeResolver(Arrays.asList(mediaTypes)));
}
/**
* Add a custom resolver.
* @param resolver the resolver to add
*/
public void resolver(RequestedContentTypeResolver resolver) {
this.candidates.add(() -> resolver);
}
/**
* Build a {@link RequestedContentTypeResolver} that delegates to the list
* of resolvers configured through this builder.
*/
public RequestedContentTypeResolver build() {
List<RequestedContentTypeResolver> resolvers =
this.candidates.isEmpty() ?
Collections.singletonList(new HeaderContentTypeResolver()) :
this.candidates.stream().map(Supplier::get).collect(Collectors.toList());
return exchange -> {
for (RequestedContentTypeResolver resolver : resolvers) {
List<MediaType> type = resolver.resolveMediaTypes(exchange);
if (type.isEmpty() || (type.size() == 1 && type.contains(MediaType.ALL))) {
continue;
}
return type;
}
return Collections.emptyList();
};
}
/**
* Helper to create and configure {@link ParameterContentTypeResolver}.
*/
public static class ParameterResolverConfigurer {
private final Map<String, MediaType> mediaTypes = new HashMap<>();
@Nullable
private String parameterName;
/**
* Configure a mapping between a lookup key (extracted from a query
* parameter value) and a corresponding {@code MediaType}.
* @param key the lookup key
* @param mediaType the MediaType for that key
*/
public ParameterResolverConfigurer mediaType(String key, MediaType mediaType) {
this.mediaTypes.put(key, mediaType);
return this;
}
/**
* Map-based variant of {@link #mediaType(String, MediaType)}.
* @param mediaTypes the mappings to copy
*/
public ParameterResolverConfigurer mediaType(Map<String, MediaType> mediaTypes) {
this.mediaTypes.putAll(mediaTypes);
return this;
}
/**
* Set the name of the parameter to use to determine requested media types.
* <p>By default this is set to {@literal "format"}.
*/
public ParameterResolverConfigurer parameterName(String parameterName) {
this.parameterName = parameterName;
return this;
}
/**
* Private factory method to create the resolver.
*/
private RequestedContentTypeResolver createResolver() {
ParameterContentTypeResolver resolver = new ParameterContentTypeResolver(this.mediaTypes);
if (this.parameterName != null) {
resolver.setParameterName(this.parameterName);
}
return resolver;
}
}
}