Spring MVC 静态资源的配置
SpringMVC在web.xml中按照如下的配置
<servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
为了RESTful,DispatcherServlet拦截了所有的访问请求,URL没有后缀
但是这样一来,资源文件如.js .css等,也会被DispatcherServlet,并尝试去找相应的controller,所以如果不配置的话静态资源就访问不到了
方案一:配置web.xml 使用default servlet处理静态资源。这样一来,资源请求不会进入DispatcherServlet,估计是最快的方案。
<servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.image</url-pattern> <url-pattern>*.css</url-pattern> <url-pattern>*.ico</url-pattern> <url-pattern>*.png</url-pattern> <url-pattern>*.js</url-pattern> </servlet-mapping>
Tomcat, Jetty, JBoss, and GlassFish 默认 Servlet "default"
Google App Engine 默认 Servle "_ah_default"
Resin 默认 Servlet "resin-file"
WebLogic 默认 Servlet "FileServlet"
WebSphere 默认 Servlet "SimpleFileServlet"
或者这样也行:
<servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/static/*</url-pattern> </servlet-mapping>
方案二:不用RESTful 加上前缀或后缀,使得DispatcherServlet不能匹配静态资源地址
<servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/app</url-pattern> </servlet-mapping>
或者
<servlet-mapping> <servlet-name>springapp</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
方案三:DispatcherServlet拦截后再给default servlet处理
<mvc:resources mapping="/resources/**" location="/resources/" /> <mvc:resources mapping="/js/**" location="/js/" /> <mvc:resources mapping="/views/**" location="/views/" /> <mvc:resources mapping="/Ext/**" location="/Ext/" /> <mvc:resources mapping="/css/**" location="/css/" />
也可以
<mvc:default-servlet-handler/>
前两种方案,spring的interceptor不能拦截静态资源
相关推荐
yupi0 2020-10-10
spring 2020-08-18
编程点滴 2020-07-29
幸运小侯子 2020-07-05
itjavashuai 2020-07-04
qingjiuquan 2020-06-29
shushan 2020-06-25
小鱿鱼 2020-06-22
咻pur慢 2020-06-18
melonjj 2020-06-17
qingjiuquan 2020-06-13
neweastsun 2020-06-05
小鱿鱼 2020-06-05
mxcsdn 2020-05-31
吾日五省我身 2020-05-27
牧场SZShepherd 2020-05-27
sweetgirl0 2020-05-14