Spring配置中对静态资源的正确引用!

来源:互联网 发布:哪个洗衣店好 知乎 编辑:程序博客网 时间:2024/06/05 19:22

web.xml中,对servlet的配置,现在一般会选择如下的配置:

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

它会过滤所有的请求,这个时候访问静态资源,例如:css文件,JavaScript文件,图片等。

会报如下警告:

警告: No mapping found for HTTP request with URI [/Spring_mvc_test/css/main.css] in DispatcherServlet with name 'springmvc'!

这个是因为web.xml配置的spring mvc过滤了所有的请求,然后在controller控制器中查找对应的请求,找不到响应的控制请求,就会报以上警告。为了能正常的访问静态资源,需要加入以下配置:

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

除了加入该配置以外,也要在beans中引用相应的网址,如下:

xmlns:mvc="http://www.springframework.org/schema/mvc"

   

http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd

此时再访问相应的网站时,会报404错误,访问不到对应的网址。因为加入静态资源的引用,<resources/>元素会阻止控制器的调用,也要相应加入<mvc:annotation-driven />,才能解决404错误。如果没有<resources/>元素,也不需要<mvc:annotation-driven />元素。


下面是我的spring-mvc文件简单配置:

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"  xsi:schemaLocation="http://www.springframework.org/schema/tx    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd    http://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsdhttp://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-3.1.xsdhttp://www.springframework.org/schema/context      http://www.springframework.org/schema/context/spring-context-3.1.xsd  http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd"><mvc:annotation-driven></mvc:annotation-driven><mvc:resources mapping="/css/**" location="/css/"/><mvc:resources mapping="/image/**" location="/image/"/><mvc:resources mapping="/*.html" location="/"/>    </beans>