您的位置:首页 > 编程语言 > Java开发

SpringMVC REST 风格静态资源访问配置

2014-07-29 21:38 531 查看
1 在web.xml中使用默认servlet处理静态资源,缺点是如果静态资源过多,则配置量会比较大,一旦有遗漏,则会造成资源无法正常显示或404错误。

<!-- 静态资源访问控制 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<!-- rest风格的拦截,需进行静态资源访问配置 -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>


2 在springmvc配置文件中配置

我的所有静态资源都在WebContent/static/之下,下有如下目录WebContent/static/img,WebContent/static/css,WebContent/static/js等等,在springmvc配置文件中添加如下配置,以下两个配置二选一即可,当然配置两最小的是第二种了,第一种的优势在于可以自主定制,可以规定哪些静态资源是可以访问的,哪些是不能访问的。

<!--静态资源的访问配置,文件夹配置,二选一 -->
<mvc:resources mapping="/static/**" location="/static/" cache-period="31556926"/>
<!--静态资源的访问配置,文件夹配置,二选一 -->
<mvc:default-servlet-handler/>


FAQ:

如果在配置文件中无法使用<mvc:相关的标签,可能是你未引入xmlns:mvc="http://www.springframework.org/schema/mvc"命名空间,其次spring版本3.0以上,我的是3.0.5版本的,测试可行。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">[/code] 
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: