在使用RESTful URI之前必须扫清对静态资源访问的问题,相信大家以前都用UrlRewrite Filter方式对配置uri pattern的静态资源进行URL rewrite.自从Spring3支持RESTful uri后,最新的Spring3.0.4巧妙的解决了对静态资源的访问,解决了开发时期对静态资源访问的问题.
先说下Spring3.0.4对静态资源访问的原理.通过<resources/>或者<mvc:resources/>元素,把mapping的URI注册到SimpleUrlHandlerMapping的urlMap中,key为mapping的URI pattern值,而value为ResourceHttpRequestHandler,这样就巧妙的把对静态资源的访问由HandlerMapping来得到ResourceHttpRequestHandler来处理返回,所以就支持classpath目录,jar包内静态资源的访问.
配置过程遇到的问题主要还是启动时BeanDefinitionXMLParser认不出<resources/>,<mvc:resources/>元素而抛出的异常.解决的方法一是正确的xmlns,xsi:schemaLocation.如下:
for <resources/>
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<resources mapping="/js/**" location="/js/" />
<resources mapping="/image/**" location="/image/" />
for <mvc:resources/>
<?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: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/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">
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/image/**" location="/image/" />
光有这些xml头还不行,需要对http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd查找的问题.她会到classpath中查找,所以只须把org.springframework.web.servlet-3.0.4.RELEASE.jar放到web lib目录下,就能查找到xsd,并不需要在IDE中自定义一个User Specified Entries.
另外需要注意的一点是,不要对SimpleUrlHandlerMapping设置defaultHandler.因为对static uri的defaultHandler就是ResourceHttpRequestHandler,否则无法处理static resources request.
但还有个问题困扰这我没搞明白.我这个web工程已对org.springframework.web.servlet.3.0.4(原码工程导入)工程依赖的,为什么非要把org.springframework.web.servlet-3.0.4.RELEASE.jar放入到web lib下才查找到spring-mvc-3.0.xsd?为什么不到依赖的org.springframework.web.servlet.3.0.4原码工程中查找spring-mvc-3.0.xsd?