<mvc:default-servlet-handler/>使用介绍

Tomcat, Jetty 等)默认的 Servlet,以便能够处理静态资源请求,如 HTML 文件、图片、CSS 文件、JavaScript 文件等。在 Spring MVC 的上下文中,静态资源默认会被当作请求映射处理,这可能会导致静态资源无法正确加载。使用 mvc:default-servlet-handler/ 可以解决这个问题。

  • 使用介绍
    添加依赖:
    确保你的项目中包含了 Spring MVC 的相关依赖。

  • 配置 Spring MVC:
    在 Spring MVC 的配置文件(通常是 spring-mvc-servlet.xml 或类似的名称)中,添加 mvc:default-servlet-handler/ 元素。

<?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 https://www.springframework.org/schema/context/spring-context.xsd 
       http://www.springframework.org/schema/mvc 
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--组件扫描...-->
    <!--视图解析器...-->

    <!-- 添加默认 Servlet 处理器 -->
    <mvc:default-servlet-handler/>

    <!-- 其他配置 ... -->

</beans>

配置静态资源位置(可选):
虽然 mvc:default-servlet-handler/ 可以处理静态资源,但你可能还需要指定静态资源的位置。这可以通过 mvc:resources 元素完成。

<mvc:resources mapping="/resources/**" location="/resources/"/>

上述配置将 /static/** 路径下的请求映射到项目的 /static/ 目录下。

测试访问静态文件:http://localhost:8080/static/image/haha.JPG

注意事项:
mvc:default-servlet-handler/ 的主要作用是告诉 Spring MVC,如果控制器没有匹配到相应的请求映射,那么请求应该被转发到 Servlet 容器默认的 Servlet(通常是处理静态资源的 Servlet)上。
使用 mvc:default-servlet-handler/ 时,不需要再为静态资源编写特定的控制器映射。
如果你同时使用了 mvc:resourcesmvc:default-servlet-handler/mvc:resources 将具有更高的优先级,因为它更具体地指定了静态资源的位置和映射。
在某些情况下,你可能还需要配置你的 Servlet 容器,以便它能够正确地处理静态资源。这通常涉及到配置 web.xml 文件或 Servlet 容器的其他配置文件。

posted @ 2024-07-08 10:14  文采杰出  阅读(2)  评论(0编辑  收藏  举报