【发布时间】:2011-06-05 04:28:03
【问题描述】:
在我的web.xml 中,默认的servlet 映射,即/,被映射到Spring dispatcher。在我的 Spring 调度程序配置中,我有 DefaultAnnotationHandlerMapping、ControllerClassNameHandlerMapping 和 AnnotationMethodHandlerAdapter,它们允许我通过类名或 @Requestmapping 注释将 url 映射到控制器。但是,在 web 根目录下有一些静态资源,我还希望 spring 调度程序使用默认 servlet 提供服务。根据Spring documentation,这可以使用<mvc:default-servlet-handler/>标签来完成。
在下面的配置中,我标记了 4 个可以插入此标签的候选位置。将标签插入不同的位置会导致调度程序的行为不同,如下所示:
案例 1:如果我将其插入位置 1,调度程序将不再能够通过 @RequestMapping 和控制器类名称处理映射,但它将正常提供静态内容。
Cas 2, 3 : 可以通过@RequestMapping 和控制器类名来处理映射,如果其他映射不能成功,也可以提供静态内容。
案例 4:它将无法提供静态内容。 删除注意:这是实现具有映射方法的控制器时的错误到/**,但在控制器类名上没有明确的请求映射。
因此,Case 2 和 3 是可取的。根据 Spring 文档,此标记配置了一个处理程序,该处理程序的优先级顺序为最低,那么为什么位置很重要?以及放置这个标签的最佳位置是?
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="webapp.controller"/>
<!-- Location 1 -->
<!-- Enable annotation-based controllers using @Controller annotations -->
<bean id="annotationUrlMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<!-- Location 2 -->
<bean id="controllerClassNameHandlerMapping" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!-- Location 3 -->
<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<!-- Location 4 -->
<mvc:default-servlet-handler/>
<!-- All views are JSPs loaded from /WEB-INF/jsp -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
【问题讨论】:
标签: java spring-mvc