簡體   English   中英

轉發不會更改瀏覽器地址欄中的URL

[英]A forward does not change the URL in browser address bar

我剛開始使用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);
}

但有些東西不起作用,因為我想要這樣的東西:

  1. 如果用戶有活動會話並且已登錄到系統“zalogowany”應該顯示
  2. 記錄表格

問題是我做的事情,那些轉發沒有把我放到我的項目的根文件夾中的index.jsp,我仍然在我的地址欄Projekt / Hai。

如果這確實是你唯一的問題

問題是我做的事情,那些轉發沒有把我放到我的項目的根文件夾中的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)並實現servlet的doGet()以顯示JSP:

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

也可以看看:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM