<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:resources 和 mvc:default-servlet-handler/,mvc:resources 将具有更高的优先级,因为它更具体地指定了静态资源的位置和映射。
在某些情况下,你可能还需要配置你的 Servlet 容器,以便它能够正确地处理静态资源。这通常涉及到配置 web.xml 文件或 Servlet 容器的其他配置文件。
- 补充:
mvc:default-servlet-handler/启用的Servlet容器也就是我用的tomcat中的配置
web.xml也有对应的
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY