spring mvc如何绕过DispatcherServlet获取* .html文件?

时间:2010-12-13 19:41:46

标签: servlets spring-mvc web.xml

web.xml片段

<!-- Handles all requests into the application -->
<servlet>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/app-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

它工作正常,但我不想让Dispatcher Servlet处理* .html请求。我该怎么做?谢谢。

5 个答案:

答案 0 :(得分:24)

在Spring MVC 3.x中,default servlet handler可以解决这个问题。

只需将其添加到Spring XML配置:

<mvc:default-servlet-handler/>

答案 1 :(得分:5)

将其映射到更具体的url-pattern

<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/spring/*</url-pattern>
</servlet-mapping>

创建一个映射在Filter上的/*

<filter-mapping>
    <filter-name>Your Dispatcher Filter</filter-name>
    <url-pattern>/*</url-pattern>
<filter-mapping>

doFilter()方法中的以下内容。

String uri = ((HttpServletRequest) request).getRequestURI();
if (uri.endsWith(".html")) {
    chain.doFilter(request, response); // Just let it go (assuming that files are in real not placed in a /spring folder!)
} else {
    request.getRequestDispatcher("/spring" + uri).forward(request, response); // Pass to Spring dispatcher servlet.
}

答案 2 :(得分:2)

<url-pattern>/*</url-pattern> 

可以像/index/*.html/*.jsp ...一样捕获,并提供给DispatcherServlet。

<url-pattern>/</url-pattern> 

只能抓住/index/main ...,不带后缀。

答案 3 :(得分:2)

Lari的解决方案(上图)很棒,并为我工作,但你必须非常小心你编写指令的顺序,它必须在文档的开头!

在我的情况下是这样的:

<mvc:annotation-driven />
<mvc:default-servlet-handler/>

<context:annotation-config />
<context:component-scan base-package="org.civitana.controller" />

答案 4 :(得分:0)

尝试将此添加到Spring XML配置中:

<!-- This will override the default DefaultAnnotationHandlerMapping that is created,
  -  and not map file extensions automagically -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="useDefaultSuffixPattern" value="false"/>
</bean>

这将阻止Spring自动将带有.html的请求映射到您的控制器。例如。 @RequestMapping(value = "/products/widgets", method = RequestMethod.GET)通常会捕获/products/widgets.html以及/products/widgets的URI。添加上述XML会强制Spring对URI模式进行精确匹配(只有后者匹配)。