12

我不知道这对于这个网站是否是一个有效的问题,但我想知道是否有人对 ContentNegotiatingViewResolver 有经验的人可以查看一下,如果我设置正确并帮助我发送 404 消息,请告诉我。

我想做的是将所有没有扩展名的url默认为HTML表示(在我的例子中是freemarker视图)。我想接受附加了“.json”的url来渲染json。这似乎适用于Firefox,即和chrome。我猜它适用于其他浏览器?我确保禁用了接受标头,因为它是一个邪恶的功能,并不像文档所说的那样真正起作用。

我尝试使用“.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>
4

2 回答 2

1

Because you have defaultContentType set, the negotiation always ends up finding a matching content type delivered by the freemarker view. A quote from the javadoc of ContentNegotiatingViewResolver:

You can also set the setDefaultContentType directly, which will be returned when the other mechanisms (Accept header, file extension or parameter) do not result in a match.

With this setting, file extension .stuff matches contentType text/html.

Then, with useNotAcceptableStatusCode:

406 (Not Acceptable) status code will be returned if no match is found.

I just tried this (with the settings of another REST service app) and saw Chrome showing the message: The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers().

于 2012-01-02T18:19:01.597 回答
0

您是否将“.stuff”的 url-pattern 添加到 web.xml?我正在使用 PathExtensionContentNegotiationStrategy,但应该是相同的原因。因为spring servlet无法响应这个请求,所以报404错误,不是500或者416。如果是416,应该是引起了一些header,可以通过改变jQuery seeting或者http client header来解决。

于 2013-08-30T05:26:58.633 回答