Spring MVC报错:无法打开/WEB-INF/dispatcher-servlet.xml资源求助
问题分析与解决方案
我帮你梳理下问题根源和解决步骤,这个问题主要是配置路径错误加上Spring MVC上下文配置的混淆导致的:
核心问题点
- 路径配置错误:你在
context-param里写的/web/WEB-INF/dispatcher-servlet.xml多了个/web前缀。ServletContext的资源路径是以Web应用根目录为起点的,正确的路径应该是/WEB-INF/dispatcher-servlet.xml。 - 上下文配置混淆:
context-param是用来配置全局Root ApplicationContext的,而DispatcherServlet默认会自动加载自己的配置文件/WEB-INF/${servlet-name}-servlet.xml(也就是你的dispatcher-servlet.xml),你当前的配置属于重复加载且路径错误,自然找不到文件。
解决方案
方案一:使用DispatcherServlet默认配置(推荐)
直接移除多余的context-param,让DispatcherServlet自动加载默认路径的配置文件,修改后的web.xml如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
方案二:手动指定DispatcherServlet的配置文件路径
如果需要明确指定配置文件位置,建议给DispatcherServlet添加init-param(而非全局的context-param),修改后的web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
额外优化:补全dispatcher-servlet.xml的Schema声明
你的配置文件缺少context和mvc命名空间的Schema地址,可能导致后续MVC注解失效,建议补全并启用注解驱动:
<?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.springWeb" /> <!--Provide support for conversion, formatting and validation --> <mvc:annotation-driven /> <!-- 启用@RequestMapping等MVC注解支持 --> </beans>
最后确认文件位置
确保dispatcher-servlet.xml确实在正确的目录下:
- Maven项目:
src/main/webapp/WEB-INF/ - 普通动态Web项目:
WebContent/WEB-INF/
内容的提问来源于stack exchange,提问作者lyes
相关产品推荐
相关产品推荐

