初学Springmvc的人都会碰到一个令人头痛的问题
那就是为什么我配置好web.xml中的dispatchservlet后,js,css,甚至gif都不能正常显示了
我们来看看我们配置的web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 核心servlet控制器 -->
<servlet>
<servlet-name>spring-mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</init-param>
</servlet>
其中url-pattern:
url-pattern有5种配置模式:
(1)/xxx:完全匹配/xxx的路径
(2)/xxx/*:匹配以/xxx开头的路径,请求中必须包含xxx。
(3)/*:匹配/下的所有路径,请求可以进入到action或controller,但是转发jsp时再次被拦截,不能访问jsp界面。
(4).xx:匹配以xx结尾的路径,所有请求必须以.xx结尾,但不会影响访问静态文件。
(5)/:默认模式,未被匹配的路径都将映射到刺servlet,对jpg,js,css等静态文件也将被拦截,不能访问。
如果我们一开始就采用了/的方式,那么就需要补上如下的web.xml配置来让静态文件可访问了。因为spring mvc默认拦截所有请求,所以你需要单独把静态资源配起来,springmvc就会放过这些请求了。
方法一:在web.xml文件中添加xml配置,
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
...
...
方法二:在applicationContext.xml配置中添加
先需要开启mvc的配置
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="...
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"
<mvc:default-servlet-handler/>
方法三: 在applicationContext.xml配置中添加
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/imgs/**" location="/imgs/" />
注意: css,js,images文件夹放于WebContent目录下。
好了。
凡是在jsp中需要访问这些资源的,可以使用
如<link rel="stylesheet" href="<%=request.getContextPath() %>/css/main.css" type="text/css" />
以上几种方法经过测试是可以成功的!
---------------------
作者:caychen
来源:CSDN
原文:https://blog.csdn.net/caychen/article/details/79625462