调用Servlet时出现HTTP Status 404 – Not Found错误求助
解决JSP提交到Servlet出现404错误的问题
你遇到的HTTP 404错误说明请求的Servlet路径无法被服务器找到,以下是几个常见的排查和解决方向:
1. 修正表单的action路径
你的JSP表单中action="Index"是相对路径,如果项目部署时有上下文路径(比如项目名为MyWebApp,访问路径是http://localhost:8080/MyWebApp/),直接写Index会导致请求路径跳过项目上下文,变成http://localhost:8080/Index,自然找不到目标Servlet。
修改JSP的表单action,自动适配项目上下文路径:
<form action="${pageContext.request.contextPath}/Index" method="get"> <input type="text" name="username"> <br> <input type="text" name="password"> <br> <input type="submit"> </form>
${pageContext.request.contextPath}会自动获取当前项目的上下文路径,确保请求能正确指向Servlet。
2. 确认Servlet已被正确编译和部署
- 检查项目编译目录(比如Maven项目的
target/classes、Eclipse的build/classes)下是否存在IndexServlet.class文件,如果没有,说明Servlet代码未被编译,需检查IDE编译配置或手动触发编译。 - 查看服务器部署目录(比如Tomcat的
webapps/你的项目名/WEB-INF/classes),确认IndexServlet.class存在且路径正确(你的代码无包名,直接放在classes根目录即可)。
3. 验证@WebServlet注解是否生效
Servlet 3.0及以上版本才支持注解式映射,需确保:
- 项目的
web.xml版本为3.0或更高(根标签web-app的version属性至少为3.0),且未设置metadata-complete="true"(该属性设为true会禁用注解扫描)。 - 若Servlet版本低于3.0,需在
web.xml中手动配置Servlet映射,示例如下:
<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"> <servlet> <servlet-name>IndexServlet</servlet-name> <servlet-class>IndexServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>IndexServlet</servlet-name> <url-pattern>/Index</url-pattern> </servlet-mapping> </web-app>
4. 确认请求方式匹配
你的表单默认使用GET方法提交,Servlet重写了doGet方法,这部分是匹配的。如果后续改成POST提交,记得重写doPost方法,或者在doGet中调用doPost逻辑。
按照以上步骤排查后,即可解决404错误,实现点击提交后Servlet输出「Hi + 用户名」的功能。
内容的提问来源于stack exchange,提问作者Danica Mora
相关产品推荐
相关产品推荐

