基于Maven的Spring MVC项目提交表单访问/add接口返回404错误求解
问题排查与修复方案
1. 核心配置缺失/错误项
- DispatcherServlet配置文件规则不匹配
Spring MVC默认要求DispatcherServlet的配置文件放置在WEB-INF目录下,命名格式为<servlet-name>-servlet.xml,你当前servlet-name为dispatcher,所以配置文件名必须为dispatcher-servlet.xml,文件名/路径错误会导致Spring无法加载配置、扫描不到Controller。 - mvc注解驱动未开启
你的dispatcher配置中缺少<mvc:annotation-driven/>,该配置是@RequestMapping等注解生效的必要前提,缺失后Spring无法识别你定义的接口路径。 - 视图解析器未配置
Controller返回字符串welcome时,Spring需要通过视图解析器拼接出完整的视图资源路径,缺失该配置会导致即使请求到Controller,也找不到返回的页面触发404。 - load-on-startup被注释
web.xml中<load-on-startup>1</load-on-startup>被注释后,DispatcherServlet会在第一次请求时才初始化,若配置存在错误不会在服务启动阶段暴露,也可能导致首次请求404。 - web.xml版本过低
当前使用的web-app 2.3版本和你依赖的Servlet 3.1 API不兼容,可能引发注解支持异常。
2. 具体修改步骤
1) 调整dispatcher-servlet.xml配置
补充缺失的配置项:
<?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:p="http://www.springframework.org/schema/p" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.first"/> <mvc:default-servlet-handler/> <!-- 新增注解驱动配置 --> <mvc:annotation-driven/> <!-- 新增视图解析器配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
之后在WEB-INF目录下创建views文件夹,新建welcome.jsp写入测试内容。
2) 调整web.xml配置
首先升级web.xml头部到3.1版本,再取消load-on-startup的注释:
<?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_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 取消注释,启动时就初始化DispatcherServlet --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3) 修正index.jsp的请求路径
避免相对路径错误,将form的action改为绝对路径写法:
<form action="${pageContext.request.contextPath}/add">
修改完成后重启服务即可,若仍有错误可查看服务启动控制台的报错信息进一步定位。
内容的提问来源于stack exchange,提问作者Mohammed Athar
相关产品推荐
相关产品推荐

