Servlet表单action路径困惑:doGet正常doPost报404资源不存在
解决Servlet doPost请求404的常见问题
Hey there, let's work through your doPost 404 issue—this is one of the most common Servlet pitfalls, so let's break down the likely culprits step by step:
1. 表单action路径是重灾区
90%的情况下,这个问题都出在表单的提交路径上。你得确保:
- 表单的
action属性和Servlet的映射路径完全匹配。比如如果你的Servlet用注解@WebServlet("/myServlet"),那表单的action不能写成action="myServlet"(相对路径可能出错)或者action="/wrongPath"。 - 推荐用动态路径避免上下文路径问题:
action="${pageContext.request.contextPath}/myServlet",这样不管你的项目部署时的上下文路径是什么,都能正确指向Servlet。 - 别犯低级错误:不要加
.java/.class后缀,也不要漏写开头的斜杠(如果是绝对路径)。
2. 检查doPost方法的签名是否完全正确
Servlet容器只会识别严格符合规范的doPost方法,哪怕一个细节错了,容器都会认为这个Servlet没有实现doPost逻辑,直接返回404/405。正确的签名必须是:
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 你的业务逻辑 }
- 一定要加
@Override注解,这样编译器会帮你校验是否正确重写了父类HttpServlet的方法。 - 注意参数类型、访问修饰符(必须是
protected)、抛出的异常,一个都不能错。
3. 注解配置的细节要到位
你说已经移除了web.xml的映射改用注解,那要确认:
@WebServlet注解的路径配置正确,比如@WebServlet("/myServlet")(简写)或者@WebServlet(urlPatterns = "/myServlet")(完整写法)。- 你的Servlet类必须继承
HttpServlet,不然容器根本不会把它当成Servlet处理。
4. 重定向路径别踩坑
虽然你的doGet重定向正常,但doPost的重定向路径也要注意:
- 如果用相对路径重定向,比如
response.sendRedirect("postSuccess.jsp"),这个路径是相对于当前Servlet的路径(比如/myServlet/postSuccess.jsp),如果目标页面在项目根目录,应该写成:
response.sendRedirect(request.getContextPath() + "/postSuccess.jsp");
这样才能正确指向根目录下的页面,避免因路径错误导致的404。
示例代码参考
正确的Servlet实现
@WebServlet("/myServlet") public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendRedirect(request.getContextPath() + "/getSuccess.jsp"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 这里可以加你的业务逻辑,比如处理表单参数 String username = request.getParameter("username"); System.out.println("收到Post请求,用户名:" + username); response.sendRedirect(request.getContextPath() + "/postSuccess.jsp"); } }
正确的表单写法
<form action="${pageContext.request.contextPath}/myServlet" method="post"> <label>用户名:</label> <input type="text" name="username"> <button type="submit">提交Post请求</button> </form>
先按上面的几点逐一排查,尤其是表单路径和doPost方法签名,这两个是最容易出错的地方。
内容的提问来源于stack exchange,提问作者MadMax
相关产品推荐
相关产品推荐

