你可以重新排序Spring MVC用来确定所请求内容的三个策略

时间:2016-07-01 13:53:01

标签: java spring spring-mvc filepath

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

  1. PathExtension(网址中的文件扩展名)
  2. pathParameter
  3. 接受标题
  4. 我可以重新排序这些弹簧会先检查Accept Header吗?喜欢

    1. 接受标题
    2. PathExtension
    3. pathParameter

1 个答案:

答案 0 :(得分:1)

为此,您需要自定义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);
    }
}

然后您可以在弹簧配置中使用此工厂bean:

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
<bean id="contentNegotiationManager" class="com.yourcompany.MyCustomContentNegotiationManagerFactoryBean"/>

基于注释的配置

要在基于注释的配置中配置ContentNegotiationManager,请删除@EnableWebMvc注释并使用您的配置类扩展WebMvcConfigurationSupportDelegatingWebMvcConfiguration。然后,您要覆盖WebMvcConfigurationSupport的{​​{3}}。该方法负责ContentNegotiationManager的实例化。

不要忘记添加@Bean注释来覆盖方法。

相关问题