若将DispatcheServlet请求映射设置为/,则SpringMvc将捕获WEB容器的所有请求,包括静态资源的请求,SpringMvc会将它们当成一个普通的请求处理,那么将会出现因找不到对应的处理器将导致错误。可在SpringMvc的配置中配置<mvc:default-servlet-handler/>的方式解决静态资源的问题:
-<mvc:default-servlet-handler/>将在SpringMvc上下文中定义一个DefaultServletHttpRequestHandler,它会对进入DispatcheServlet的请求进行筛选,如果发现没有经过映射的请求,就将该请求交由WEB应用服务器默认的Servlet处理,如果不是静态资源的请求,才由DispatcheServlet处理。
-一般WEB应用服务器默认的Servlet名称都是default,若使用的WEB应用服务器的默认Servlet不是default,则需要通过default-servlet-name属性显式指定。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<?
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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置自动扫描的包-->
<
context:component-scan
base-package="com.seven"></
context:component-scan
>
<!--配置视图解析器,将视图逻辑名解析为/WEB-INF/pages/<viewName>.jsp-->
<
bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<
property
name="prefix" value="/WEB-INF/pages/"/>
<
property
name="suffix" value=".jsp"/>
</
bean
>
<!--
<mvc:annotation-driven/>在实际开发中都需要配置,而且如果不配置,那么 <mvc:default-servlet-handler/>
就会出问题,老是找不到要访问的资源。因为这个标签会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,
是spring MVC为@Controllers分发请求所必须的。(当然也可以手动配置这两个bean,但是比较麻烦)
-->
<
mvc:annotation-driven
/>
<
mvc:default-servlet-handler
/>
<!--配置直接转发的页面,可以直接转到相应转发的页面,而不用经过handler-->
<!--path属性是访问资源时的URL路径,view-name是资源的视图名-->
<
mvc:view-controller
path="/success" view-name="hu"/>
<!--
<mvc:resources mapping="/images" location=""/>
这个标签是为了将访问资源文件的路径映射到实际的目录
-->
</
beans
>
|