700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > spring mvc静态资源访问的配置

spring mvc静态资源访问的配置

时间:2023-03-20 21:03:32

相关推荐

spring mvc静态资源访问的配置

如果我们使用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""/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="/schema/beans"xmlns:context="/schema/context"xmlns:xsi="/2001/XMLSchema-instance" xmlns:mvc="/schema/mvc"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans.xsd/schema/mvc /schema/mvc/spring-mvc.xsd/schema/context /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>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。