How to use redirect methods with Java Servlets

Asked

Viewed 1,392 times

5

Hello, I have a page ordem_servico.jsp with a form that when submitted goes to Servletinsertordemservico which inserts the form data into the database.
I am trying to make sure that when the data is entered, the browser returns to the page ordem_servico.jsp and present a Alert javascript saying that the order was successfully inserted, my code is like this:

    RequestDispatcher rd;
    if( dao.cadastrarOS(os) ) {
        rd = getServletContext().getRequestDispatcher("/paginas/ordem_servico.jsp");
        rd.include(request, response);
        out.print(
            "<script type=\"text/javascript\">"
                +"alert(\“Ordem inserida com sucesso!\”);"+
            "</script>"
        );
    }

This code is doing exactly what I want, but this getRequestDispatcher() redirects to http://localhost:8080/Servletinsertordemservico , and I can no longer access any internal link of the page, because the links to other pages are obviously out of Servlet context, and so glassfish returns error 404.

Instead of using getRequestDispatcher(), I’ve tried using getRequestDispatcher( Response.sendRedirect("pages/ordem_servico.jsp"), in this case I can enter the data and access the internal links, but the javascript Alert nay is presented.

Anyone who’s ever been in this situation would have some suggestion?

I thank you all!

  • Actually with the above code it shows Alert, the problem is that I can’t access internal links, because getRequestDispatcher redirects to Servlet and not to jsp, and if I use Response.sendRedirect, it redirects to jsp, but does not display Alert, thank you Renan!

  • Also no, it redirects to Servlet the same way

  • This code is inside JSP or Servlet?

1 answer

1

Although your approach is working, it’s way out of the box. An alternative and more interesting way would be to fix the alert on your page JSP and only display it if it passes on condition that the data has been entered successfully.

In his JSP, would look something like this:

<script>

document.onload = function() {

    if(${sessionScope.resultado} == "sucesso"){
        alert("Ordem inserida com sucesso!");
    }

};

</script>

Now, on your Servlet, the code would look something like this:

if(dao.cadastrarOS(os)) {
    request.getSession().setAttribute("resultado", "sucesso");
    response.sendRedirect("/paginas/ordem_servico.jsp");
}

UNDERSTANDING WHY THE SESSION

What would be common use is the request.setAttribute(), however, you will not have access to request when using and sendRedirect() by Sponse. You will soon have to use the session since he is persistent among several requests.

Do not forget to remove the "result" attribute in session to reuse it for other purposes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.