NetBeans+GlassFish中JSP移入LoginOut文件夹后出现HTTP 404错误求助
解决JSP移入文件夹后出现HTTP 404的问题
嘿,我完全懂你碰到的这个头疼问题——好好的项目,把JSP归类到新建的LoginOut文件夹就404,移回去又正常,这大概率是路径映射没跟上文件位置变化导致的,咱们一步步拆解解决:
问题根源分析
你代码里的这些地方,都依赖原来的JSP文件路径,当文件移到LoginOut文件夹后,旧路径自然就找不到资源了:
- Servlet的转发路径:
LoginServlet里的destPage = "Login.jsp"是基于Web应用根目录的相对路径,现在Login.jsp在LoginOut下,这个路径就失效了。 - JSP内的链接:比如
Login.jsp里的<a href="index.jsp">,如果index.jsp不在LoginOut文件夹,点击后也会出现路径错误;另外表单的action其实也有小问题(你的Servlet注解是@WebServlet("/Login"),所以action应该写"Login"而非"LoginServlet",不过这不是当前404的主因)。
具体解决方案
1. 修正Servlet中的转发路径
把Servlet里的目标页面路径改成基于Web根目录的绝对路径(以/开头),指向LoginOut文件夹下的JSP:
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String email = request.getParameter("email"); String password = request.getParameter("pass"); try { User user = userDao.checkLogin(email, password); // 修正路径,指向LoginOut文件夹下的Login.jsp String destPage = "/LoginOut/Login.jsp"; if (user != null) { HttpSession session = request.getSession(); session.setAttribute("user", user); // 如果home.jsp也移到了对应文件夹,这里也要同步修改路径 destPage = "/home.jsp"; } else { String message = "Invalid email/password"; request.setAttribute("message", message); } RequestDispatcher dispatcher = request.getRequestDispatcher(destPage); dispatcher.forward(request, response); } catch (SQLException | ClassNotFoundException ex) { throw new ServletException(ex); } }
2. 修正JSP内的链接路径
为了避免上下文路径和相对路径的混乱,建议用${pageContext.request.contextPath}获取Web应用根路径,再拼接目标资源的绝对路径:
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Login Page</title> </head> <body> <!-- 修正表单action,匹配Servlet的注解路径 --> <form action="${pageContext.request.contextPath}/Login" method="POST"> Email: <input type="text" name="email" ><br><br> Password: <input type="password" name="pass" ><br><br> <input type="submit" value="Login" ><br><br> <!-- 修正返回链接,指向根目录下的index.jsp --> <a href="${pageContext.request.contextPath}/index.jsp">Click here to go back.</a> </form> </body> </html>
3. 额外检查点
- 确认
LoginOut文件夹确实在Web应用的根目录下(NetBeans里对应WebContent或src/main/webapp目录,别误放到src等非部署目录)。 - 执行NetBeans的
Clean and Build,然后重新部署到GlassFish,避免部署缓存导致的文件同步问题。 - 打开浏览器开发者工具(F12)查看Network面板,看404请求的具体URL,能更精准定位路径错误。
内容的提问来源于stack exchange,提问作者Edmond Dantes
相关产品推荐
相关产品推荐

