我只是从Servlets / JSP / JSTL开始,我有这样的东西:
<html> <body> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <jsp:directive.page contentType="text/html; charset=UTF-8" /> <c:choose> <c:when test='${!empty login}'> zalogowany </c:when> <c:otherwise> <c:if test='${showWarning == "yes"}'> <b>Wrong user/password</b> </c:if> <form action="Hai" method="post"> login<br/> <input type="text" name="login"/><br/> password<br/> <input type="password" name="password"/> <input type="submit"/> </form> </c:otherwise> </c:choose> </body> </html>
在我的doPost方法中
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); try { logUser(request); } catch(EmptyFieldException e) { session.setAttribute("showWarning", "yes"); } catch (WrongUserException e) { session.setAttribute("showWarning", "yes"); } RequestDispatcher d=request.getRequestDispatcher("/index.jsp"); System.out.println("z"); d.forward(request, response); }
但是有些东西行不通,因为我想要这样的东西:
问题是无论我做什么,这些转发者都不会把我放到Project.root目录中的index.jsp,而我的地址栏中仍然有Projekt / Hai。
如果那真的是你 唯一的 问题
那我就让你失望了:那完全是规范。转发器基本上告诉服务器使用给定的JSP呈现结果。它不告诉客户端在给定的JSP上发送新的HTTP请求。如果您希望客户端的地址栏中发生更改,则必须告诉客户端发送新的HTTP请求。您可以通过发送重定向而不是转发来实现。
所以,代替
RequestDispatcher d=request.getRequestDispatcher("/index.jsp"); System.out.println("z"); d.forward(request, response);
做
response.sendRedirect(request.getContextPath() + "/index.jsp");
另一种选择是/index.jsp完全删除URL并/Hai始终使用URL。您可以通过将JSP隐藏在/WEB- INF文件夹中来实现此目的(以便最终用户永远无法直接打开它,而被迫为此使用servlet的URL)并实现doGet()Servlet的来显示JSP:
/index.jsp
/Hai
/WEB- INF
doGet()
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response); }
这样,您可以打开http:// localhost:8080 / Project / Hai并查看JSP页面的输出,并且表单将只提交到相同的URL,因此浏览器地址栏中的URL基本不会改变。我可能只会将更/Hai改为更明智的内容,例如/login。
/login