我知道spring有三种策略来确定所请求的内容并返回相应的类型。spring使用这三种策略来检测。
- PathExtension (url中的文件扩展名)
- pathParameter
- Accept标头
我可以重新订购这些,以便spring首先检查接受标头吗?像
- Accept标头
- PathExtension
- pathParameter
要做到这一点,您将需要自定义ContentNegotiationManager
。默认的ContentNegotiationManagerFactoryBean
具有固定的策略顺序,当您想要自定义顺序时,建议实例化您自己的ContentNegotiationManager
,就像
new ContentNegotiationManager(strategies);
其中strategies
是按顺序排列的策略列表。
但是我相信扩展ContentNegotiationManagerFactoryBean
只是重写afterPropertiesSet
方法更容易,其中策略被创建和排序。
public class MyCustomContentNegotiationManagerFactoryBean extends ContentNegotiationManagerFactoryBean {
@Override
public void afterPropertiesSet() {
List<ContentNegotiationStrategy> strategies = new ArrayList<ContentNegotiationStrategy>();
if (!this.ignoreAcceptHeader) {
strategies.add(new HeaderContentNegotiationStrategy());
}
if (this.favorPathExtension) {
PathExtensionContentNegotiationStrategy strategy;
if (this.servletContext != null && !isUseJafTurnedOff()) {
strategy = new ServletPathExtensionContentNegotiationStrategy(
this.servletContext, this.mediaTypes);
}
else {
strategy = new PathExtensionContentNegotiationStrategy(this.mediaTypes);
}
strategy.setIgnoreUnknownExtensions(this.ignoreUnknownPathExtensions);
if (this.useJaf != null) {
strategy.setUseJaf(this.useJaf);
}
strategies.add(strategy);
}
if (this.favorParameter) {
ParameterContentNegotiationStrategy strategy =
new ParameterContentNegotiationStrategy(this.mediaTypes);
strategy.setParameterName(this.parameterName);
strategies.add(strategy);
}
if (this.defaultNegotiationStrategy != null) {
strategies.add(this.defaultNegotiationStrategy);
}
this.contentNegotiationManager = new ContentNegotiationManager(strategies);
}
}
然后你可以在你的spring配置中使用这个工厂bean:
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
<bean id="contentNegotiationManager" class="com.yourcompany.MyCustomContentNegotiationManagerFactoryBean"/>
基于注解的配置为了在基于注释的配置中配置ContentNegotiationManager
,请删除@EnableWebMvc
注释并使用配置类扩展WebMvcConfigurationSupport
或DelegatingWebMvcConfiguration
。然后你想覆盖WebMvcConfigurationSupport
的mvcContentNegotiationManager
方法。该方法负责ContentNegotiationManager
的实例化。
别忘了给重写方法添加@Bean
注释