使用< mvc:resources ... />在春季3导致所有其他视图停止工作 [英] Using <mvc:resources .../> in spring 3 causes all other views to stop working

查看:161
本文介绍了使用< mvc:resources ... />在春季3导致所有其他视图停止工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最简单的例子:

我有一个调度程序servlet配置为捕获所有内容:

I have a dispatcher servlet configured to catch everything:

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

我有一个简单的测试控制器:

I have a simple test controller:

@RequestMapping("/index")
@ResponseBody
public String rootTest(){
    return "Main page displayed from TestController";
}

在这个测试用例中,我将以下行添加(或删除)给 dispatcher-servlet.xml

In this test case I am adding (or removing) the following line to dispatcher-servlet.xml:

<mvc:resources mapping="/public/**" location="/public/"/>

我的崇高目标:提供静态内容(图片,css,js) )以及我的动态内容(通过Jetty servlet容器中的Velocity生成,与全能的Spring捆绑在一起)。

My lofty goal: to serve static content (images, css, js) along with my dynamic content (generated via Velocity within a Jetty servlet container, tied together with the almighty Spring).

我的困境:我添加< mvc:resources ... /> 我得到了一个404的 http:// localhost / index ,但我可以通过 http://localhost/public/img/42.png 。如果我删除< mvc:resources ... /> ,那么 http:// localhost / index 工作正常,但当然,我如何提供静态内容?

My Dilema: When I add <mvc:resources .../> I get a 404 for http://localhost/index, but I can serve an image from http://localhost/public/img/42.png. If I remove <mvc:resources .../> then http://localhost/index works fine, but of course, how do I serve static content?

奖金问题:为什么我从来没有吃过蛋糕呢?

Bonus question: Why can I never have my cake and eat it too?

推荐答案

有2个问题:


  1. 永远不要在servlet映射中使用 / *

<servlet-mapping> 
    <servlet-name>dispatcher</servlet-name> 
    <url-pattern>/</url-pattern> 
</servlet-mapping> 


  • < mvc:resources> 需要< mvc:annotation-driven> (或显式声明的处理程序映射等)。

  • <mvc:resources> requires <mvc:annotation-driven> (or explicitly declared handler mappings, etc).

    这是因为 DispatcherServlet 仅在上下文中找不到自定义处理程序映射时才应用处理程序映射的默认配置。由于< mvc:resources> 添加了自己的处理程序映射,因此默认值被破坏,因此其他处理程序映射应该通过< mvc显式地进行十字转换:注释驱动的> 或手动作为bean。

    This happens because DispatcherServlet applies default configuration of handler mappings only when no custom handler mappings found in the context. Since <mvc:resources> adds its own handler mapping, defaults are broken, therefore other handler mappings should be decalred explicitly, either by <mvc:annotation-driven> or manually as beans.

    另请注意< mvc:resources> 仅声明 DefaultAnnotationHandlerMapping 并且不会声明其他映射,例如 BeanNameUrlHandlerMapping ,尽管它们的默认值为 DispatcherServlet 。如果需要,可以手动声明它们。

    Also note that <mvc:resources> declares only DefaultAnnotationHandlerMapping and doesn't declare other mappings such as BeanNameUrlHandlerMapping, though they are in defaults of DispatcherServlet. Declare them manually if you need them.

    这篇关于使用&lt; mvc:resources ... /&gt;在春季3导致所有其他视图停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆