天天看点

SpringMVC-访问静态页面

处理静态数据

前面我们将DispatcherServlet请求映射配置为/,则SpringMVC会将所有不是.jsp结尾的请求都交给DispatcherServlet进行映射处理。

通常我们不希望对静态数据(js,html)进行映射,通过如下方法配置即可。

在SpringMVC配置文件中配置<mvc:default-servlet-handler/>,配置后SpringMVC会默认定义一个DefaultServletHttpRequestHandler,他会对所有没有通过DispatcherServlet映射的网址进行处理。

默认的Handler是谁?

如果使用的是tomcat,则在安装目录下的conf\web.xml文件中可以看到 default的servlet的定义。

org.apache.catalina.servlets.DefaultServlet

注意:为了让正常的@RequestMapping不会被影响,需要同时配置 <mvc:annotation-driven></mvc:annotation-driven>

对应的xml配置如下:

<?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.2.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.2.xsd">

	<context:component-scan base-package="spring"></context:component-scan>
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	<mvc:default-servlet-handler/>
	<mvc:annotation-driven></mvc:annotation-driven>
</beans>
           

<完>