您可以重新排序Spring MVC用来确定请求内容的三种策略吗?



我知道spring有三种策略来确定所请求的内容并返回相应的类型。spring使用这三种策略来检测。

  1. PathExtension (url中的文件扩展名)
  2. pathParameter
  3. Accept标头

我可以重新订购这些,以便spring首先检查接受标头吗?像

  1. Accept标头
  2. PathExtension
  3. 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注释并使用配置类扩展WebMvcConfigurationSupportDelegatingWebMvcConfiguration。然后你想覆盖WebMvcConfigurationSupportmvcContentNegotiationManager方法。该方法负责ContentNegotiationManager的实例化。

别忘了给重写方法添加@Bean注释

相关内容

最新更新