天天看点

springmvc对静态资源访问处理1、url-pattern为/2、url-pattern为/*

1、url-pattern为/

在web.xml配置前端控制器的url-pattern为/时,动态资源和配置的控制器可以访问,但html,gif图片,css,js等静态资源不可以访问了。

1.1 原因

其实在每个动态web项目下都会有个局部web.xml配置文件,tomcat下有个全局web.xml配置文件,当使用tomcat启动动态web项目时,当url-pattern为/在局部的web.xml配置,默认全局web.xml已经配置了url-pattern为/,全局web.xml的url-pattern为/,可以访问静态资源、动态资源、控制器。此时,tomcat会就近原则,选择该动态web项目的局部web.xml,从而只能访问jsp动态资源和配置的控制器,不能访问静态资源。

1.2 解决方案

第一种:springmvc.xml配置放行静态资源

mvc:default-servlet-handler是把静态资源还给全局配置web.xml的默认servlet处理。

<?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:context="http://www.springframework.org/schema/context"
	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.3.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!-- 组件包扫描 -->
	<context:component-scan base-package="cn.zj.springmvc"/>
	
	
	<!-- 设置SpringMVC的注解驱动 -->
	<mvc:annotation-driven/>
	
	
	<!-- 设置SpringMVC静态资源处理 -->
	<mvc:default-servlet-handler/>

</beans>

           

第二种:web.xml配置*.do等通配符

此时springmvc不需要配置放行静态资源mvc:default-servlet-handler标签,在web.xml配置url-pattern为*.do。当静态资源进来,不符合*.do,则走全局的web.xml,而全局的web.xml又放行静态资源,从而静态资源可以访问到。

注意:控制器访问时,需要加上.do,但@RequestMapping("/url"),url不需要添加.do。springmvc默认会给url添加.do。所以可以添,可不添。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">

	<!-- 集成配置SpringMVC -->


	<!-- 配置SpringMVC的前端控制器(总控) 让浏览器的所有请求都经过SpringMVC框架 -->
	<servlet>
		<servlet-name>MVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 配置读取配置文件的初始化参数 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<!-- 初始化容器创建所有对象 -->
		<load-on-startup>1</load-on-startup>
		
	</servlet>
	<servlet-mapping>
		<servlet-name>MVC</servlet-name>
		<!-- <url-pattern>/</url-pattern> -->
		
		<!-- 实际开发一般都喜欢通配符 * 加上后缀
			*.do , *.action (早期Struts2的风格)
		 -->
		<url-pattern>*.do</url-pattern>
		
	</servlet-mapping>
</web-app>
           

2、url-pattern为/*

在web.xml配置前端控制器的url-pattern为/*时,配置的控制器也不可以访问,html,gif图片,css,js等静态资源和动态资源(jsp)都不可以访问了。

继续阅读