简体   繁体   English

是否可以从Servlet重定向到同一个JSP页面?

[英]Is it possible to redirect to the same JSP page from a Servlet?

A JSP page named Test.jsp is mapped to the following Servlet. 名为Test.jsp的JSP页面映射到以下Servlet。

@WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})
public final class TestServlet extends HttpServlet
{
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        //request.getRequestDispatcher("/WEB-INF/admin_side/Test.jsp").forward(request, response);
       response.sendRedirect("TestServlet");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}

This Servlet is mapped to a JSP page Test.jsp . 此Servlet映射到JSP页面Test.jsp The doGet() method is invoked, when a URL like http://localhost:8080/Assignment/TestServlet is entered in the address bar. 当在地址栏中输入类似http://localhost:8080/Assignment/TestServlet的URL时,将调用doGet()方法。

The request can be forwarded to the given URL as commented out. 请求可以在注释时转发到给定的URL。 Is it possible to redirect to the same JSP page, Test.jsp ? 是否可以重定向到同一个JSP页面Test.jsp

If an attempt is made to do so, Google Chrome complains, 如果尝试这样做,Google Chrome会抱怨,

This webpage has a redirect loop 此网页有重定向循环

It can however, redirect to other pages under WEB-INF/admin_side . 但是,它可以重定向到WEB-INF/admin_side下的其他页面。

The POST-REDIRECT-GET pattern works like so. POST-REDIRECT-GET模式就像这样工作。

A client sends a POST request, your server handles it and responds with a redirect, ie. 客户端发送POST请求,您的服务器处理它并使用重定向进行响应,即。 a response with a 302 status code and Location header to the appropriate URI. 具有302状态代码和Location标头的响应到适当的URI。 The client makes a GET request to that URI. 客户端向该URI发出GET请求。

Currently, your server is redirecting on both GET and POSTS requests. 目前,您的服务器正在重定向GET和POSTS请求。 What's worse is that your GET is redirecting to the same URI that it is handling, creating the redirect loop you are seeing. 更糟糕的是,您的GET重定向到它正在处理的相同URI,创建您正在看到的重定向循环。

Change your Servlet implementation so that the POST sends a redirect, but the GET actually serves up a normal 200 response with HTML, AJAX, etc. 更改您的Servlet实现,以便POST发送重定向,但GET实际上通过HTML,AJAX等提供正常的200响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM