转发不会更改浏览器地址栏中的URL

And*_*dna 11 java jsp servlets jstl

我刚开始使用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>
Run Code Online (Sandbox Code Playgroud)

并在我的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);
}
Run Code Online (Sandbox Code Playgroud)

但有些东西不起作用,因为我想要这样的东西:

  1. 如果用户有活动会话并且已登录到系统"zalogowany"应该显示
  2. 记录表格

问题是我做的事情,那些转发没有把我放到我的项目的根文件夹中的index.jsp,我仍然在我的地址栏Projekt/Hai.

Bal*_*usC 24

如果这确实是你唯一的问题

问题是我做的事情,那些转发没有把我放到我的项目的根文件夹中的index.jsp,我仍然在我的地址栏Projekt/Hai.

然后我不得不让你失望:这完全符合规范.转发基本上告诉服务器使用给定的JSP来呈现结果.它不会告诉客户端在给定的JSP上发送新的HTTP请求.如果您希望更改客户端的地址栏,则必须告诉客户端发送新的HTTP请求.您可以通过发送重定向而不是转发来实现.

所以,而不是

RequestDispatcher d=request.getRequestDispatcher("/index.jsp");
System.out.println("z");
d.forward(request, response);
Run Code Online (Sandbox Code Playgroud)

response.sendRedirect(request.getContextPath() + "/index.jsp");
Run Code Online (Sandbox Code Playgroud)

另一种方法是/index.jsp完全删除URL并/Hai始终使用URL.您可以通过将JSP隐藏在/WEB-INF文件夹中来实现这一点(以便最终用户永远不能直接打开它并强制使用servlet的URL)并实现doGet()servlet以显示JSP:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
}
Run Code Online (Sandbox Code Playgroud)

这样,您只需打开http:// localhost:8080/Project/Hai并查看JSP页面的输出,表单将只提交到相同的URL,因此浏览器地址栏中的URL基本不会更改.我可能只会改变/Hai一些更明智的东西,例如/login.

也可以看看:

  • 为此,应使用过滤器:http://stackoverflow.com/tags/servlet-filters/info简而言之:登录成功后,将"用户"放入会话中.在过滤器中,您只需检查其存在,然后继续或相应地重定向请求. (3认同)