我的Spring-MVC ContentNegotiatingViewResolver设置正确吗?我怎样才能为不支持的媒体类型发送404错误?

12

我不确定这是否是该网站的有效问题,但我想知道熟悉ContentNegotiatingViewResolver的人能否检查一下并告诉我是否正确设置,以及帮助我发送404消息。

我想做的是使所有没有扩展名的url默认为HTML表示(在我的情况下是freemarker视图)。我想接受在它们后面添加“.json”的url以呈现json。这在火狐浏览器、IE和Chrome中似乎都可以工作。我猜这也适用于其他浏览器?我确保禁用了accept header,因为它是一个邪恶的功能,不像文档所说的那样工作。

我尝试访问带有“.stuff”后缀的url,只是看看会发生什么,按照我的配置,会出现空白屏幕。这可接受吗?有没有办法发送404错误?

还有其他我可能没有正确配置的东西吗?

<bean id="contentNegotiatingViewResolver"
      class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="order" value="1"/>
    <property name="ignoreAcceptHeader" value="true" />
    <property name="defaultContentType" value="text/html" />
    <property name="mediaTypes">
        <map>
            <entry key="json" value="application/json"/>
        </map>
    </property>
    <property name="useNotAcceptableStatusCode" value="true" />
    <property name="defaultViews">
        <list>
            <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
                <property name="contentType" value="application/json" />
            </bean>
        </list>
    </property>
    <property name="viewResolvers">
        <list>
            <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
                <property name="contentType" value="text/html" />
                <property name="order" value="2"/>
                <property name="cache" value="true"/>
                <property name="prefix" value=""/>
                <property name="suffix" value=".ftl"/>
                <property name="exposeSpringMacroHelpers" value="true"/>
            </bean>
        </list>
    </property>
</bean>
2个回答

1

由于您设置了defaultContentType,协商总是会找到由freemarker视图提供的匹配内容类型。以下是ContentNegotiatingViewResolver的javadoc引用:

您还可以直接设置setDefaultContentType,当其他机制(Accept标头、文件扩展名或参数)没有结果时,将返回该值。

使用此设置,文件扩展名.stuff与contentType text/html匹配。

然后,使用useNotAcceptableStatusCode:

如果找不到匹配项,则返回406(不可接受)状态代码。

我刚刚尝试了这个(使用另一个REST服务应用程序的设置),看到Chrome显示消息:根据请求“accept”标头,此请求标识的资源仅能生成具有不可接受特征的响应。


0
你在web.xml中添加了".stuff"的url-pattern吗?我正在使用PathExtensionContentNegotiationStrategy,但应该是同样的原因。因为Spring Servlet无法响应此请求,所以出现了404错误,而不是500或416。如果是416,则应该是由某些头部引起的,可以通过更改jQuery设置或http客户端头部来修复。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接