如果我们使用spring mvc来做web访问请求的控制转发,那么默认所有访问都将被DispatcherServlet独裁统治。比如我现在想访问的欢迎页index.html根本无需任何业务逻辑处理,仅仅就展示一句话而已,但spring mvc还是会把访问index.html这件事交给DispatcherServlet处理,而DispatcherServlet会从HandlerMapping去找对应Controller注解,如果找不到就报错了:
No mapping found for HTTP request with URI [/index.html] in DispatcherServlet with name 'service-dispatcher'
spring mvc提供的解决方案是在配置文件中加入mvc:resources来专门标识静态资源,比如我的web.xml是这样的:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Memcache View Application</display-name> <servlet> <servlet-name>service-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>service-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-core.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
那么我的spring-mvc.xml就要是这样的:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <context:component-scan base-package="com.wulinfeng.memcache.view" /> <mvc:annotation-driven /> <mvc:resources location="/" mapping="/**/*.js"/> <mvc:resources location="/" mapping="/**/*.css"/> <mvc:resources location="/" mapping="/**/*.png"/> <mvc:resources location="/" mapping="/*.html"/> </beans>
这时就可以顺利访问index.html这个欢迎页了。其他js、css或png图片的静态资源也可以直接访问。如果我还要做拦截,比如登陆功能,又不想拦截到静态资源,怎么办呢?最简单的就是配置拦截时过滤静态资源:
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**" /> <mvc:exclude-mapping path="/**/*.css" /> <mvc:exclude-mapping path="/**/*.js" /> <mvc:exclude-mapping path="/**/*.png" /> <mvc:exclude-mapping path="*.html" /> <mvc:exclude-mapping path="/login**" /> <mvc:exclude-mapping path="/register**" /> <mvc:exclude-mapping path="/getVerifyCode**" /> <mvc:exclude-mapping path="/getMethod/**" /> <bean class="com.wulinfeng.test.testpilling.util.InterceptorUtil" /> </mvc:interceptor> </mvc:interceptors>