【发布时间】:2011-10-27 01:39:38
【问题描述】:
我是spring mvc3的新手,我正在尝试创建一个简单的项目来接近spring mvc3。
现在我在尝试服务器一些静态资源文件时遇到了一些问题。
因为我在 web.xml 中使用了 url-pattern (/):
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
所以,当我输入:http://locaohost:8080/spring/res/css/main.css。我会收到 404 错误。
从spring文档中,我尝试使用<mvc:resource location="/res/" mapping="/res/**" />
但是如果我在spring-servlet.xml中添加这个标签,我发现,我现在可以获取资源文件,但是我不能访问其他页面。
也就是说,我有一个控制器:
@Controller
@RequestMapping("/example")
public class HelloController {
@RequestMapping("hello")
public String hello(Model model){
model.addAttribute("name", "John");
return "spring.example.hello";
}
}
当我访问时:http://locaohost:8080/spring/example/hello,I 现在会得到 404。
但如果我删除标签:<mvc:resource xxx/>
我可以访问http://locaohost:8080/spring/example/hello,but我无法获取 .css/.js 文件。
通过eclipse中的调试器,我发现当spring init“DispatchServlet”的“initHanderMapping”方法中的handerMapping时,创建了两个映射实例: BeanNameUrlHandlerMapping 和 SimpleUrlHandlerMapping。
BeanNameUrlHandlerMapping 的handelrMap 属性始终为空,而SimpleUrlHandlerMapping 始终包含与url 匹配的映射。
当我添加标签时,它的handerMapping属性是:{/res/**=org.springframework.web.servlet.resource.ResourceHttpRequestHandler@1120eed}
当我删除标签时,handelrMapping 是:{/example/hello=com.spring.controller.HelloController@1b5438d, /example/hello.*=com.spring.controller.HelloController@1b5438d, /example/hello/=com.spring.controller.HelloController@1b5438d}。
似乎{/res/**=xxxx} 覆盖了其他映射{/example/helloxxxxx}
这是spring-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- <mvc:resources location="/res/" mapping="/res/**"></mvc:resources>-->
<context:component-scan base-package="com.spring.controller" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.tiles2.TilesViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/jsp/tile_def.xml</value>
</list>
</property>
</bean>
</beans>
如何解决?
【问题讨论】:
标签: spring spring-mvc