A forward does not change the URL in browser address bar

前端 未结 1 1904
孤街浪徒
孤街浪徒 2020-12-10 04:24

I am just starting with Servlets/JSP/JSTL and I have something like this:



<%@taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/j         


        
相关标签:
1条回答
  • 2020-12-10 05:02

    If that is really your only problem

    the problem is whatever I do, those forwards don't put me to index.jsp, which is in root folder of my Project, I still have in my address bar Projekt/Hai.

    then I have to disappoint you: that's fully by specification. A forward basically tells the server to use the given JSP to present the results. It does not tell the client to send a new HTTP request on the given JSP. If you expect a change in the address bar of the client, then you have to tell the client to send a new HTTP request. You can do that by sending a redirect instead of a forward.

    So, instead of

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

    do

    response.sendRedirect(request.getContextPath() + "/index.jsp");
    

    An alternative is to get rid of the /index.jsp URL altogether and use /Hai URL all the time. You can achieve this by hiding the JSP away in /WEB-INF folder (so that the enduser can never open it directly and is forced to use the servlet's URL for this) and implement the doGet() of the servlet as well to display the JSP:

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

    This way, you can just open http://localhost:8080/Project/Hai and see the output of the JSP page and the form will just submit to the very same URL, so the URL in browser address bar will basically not change. I would maybe only change the /Hai to something more sensible, such as /login.

    See also:

    • RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()
    • doGet and doPost in Servlets
    • Our Servlets wiki page
    0 讨论(0)
提交回复
热议问题