Servlet: Cannot forward after response has been committed

前端 未结 4 1739
难免孤独
难免孤独 2020-12-17 06:22

I\'m working on servlet page that renders content based on geo-location, and I want to use both sendRedirect and forward together; e.g

4条回答
  •  春和景丽
    2020-12-17 06:58

    You have to be aware that a redirect is a complete response to the browser and the browser will in turn issue a new request to the url you redirected to. Even though you can't really sse it when dealing with the browser you always have to be aware that this is what happens.

    Now, if you use the same controller for the second request you have to check wether a redirect is necessary or you can now do the forward instead.

    if (!path.startsWith(locationPrefix)) {
      response.sendRedirect(locationPrefix + path);
      return;
    } else {
      RequestDispatcher view = request.getRequestDispatcher(RESOURCES_PAGE);
      view.forward(request, response);
      return;
    }
    

    Of course it would be nicer to have a distinct controller per request, but depending of url structure and framework this is not always possible.

提交回复
热议问题