SendRedirect () doesn't work

I searched for a solution on this forum, but I couldn't find anything that matched my problem.

I have a very simple code

a jsp page

<html>
<body>
<jsp:include page="/servletName"/>
</body>
</html>

      

and servlet

@WebServlet("/servletName")
public class reindirizzaController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public reindirizzaController() {
        super();        
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String redirectURL = "http://www.google.it";
      response.sendRedirect(redirectURL);       
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

}

      

No forwarding is in progress. I am stuck on the jsp page and I have no errors. I also tried adding return;

after answer.

+3


source to share


3 answers


Since you are calling the servlet through Include

, it does not redirect you. He just ignores.

From the docs include()



includes the content of the resource (servlet, JSP page, HTML file). Basically, this method includes a software backend.

The ServletResponse object has its own path elements and the parameters remain unchanged from the caller. An enabled servlet cannot change the response status code or set headers; any attempt to make changes is ignored.

+3


source


First, it is bad practice to call a servlet from jsp. When you use @WebServlet("/servletName")

you can directly call ithttp://host/context/servletName

If you really need to call it from jsp, you should send it to the servlet and not include it as Suresh Atta explained. Therefore, you must use:



<jsp:forward page="/servletName"/>

      

0


source


When you execute the JSP include directive, you are essentially clipping the code that you include right on the page. In your example, you will be doing sendRedirect in your JSP. Even if you've gotten a miraculous job of redirecting, you'll get an error stating that your answer has already been done. This is because by the time your browser loads the JSP, it is already reading the response from the server. The server cannot send another response while it is already sending the response to your browser.

One way to approach this is instead of making an include directive, create a form with your servlet path as an action. Something like:

<form name="someForm" action="/servletPath/servletName">
    <!-- some stuff here if you want -->
</form>

      

And then in your body tag, submit the form to upload:

<body onLoad="document.someForm.submit();">

      

0


source







All Articles