How to use redirect methods with Java Servlets

5

Hello, I have a server_server.jsp page with a form that when submitted goes to ServletInsertOrderService that inserts the form data into the database. I am trying to cause that when the data is entered, the browser returns to the server_server.jsp page and displays a alert of the 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 link , and I can no longer access any internal links on the page, since the links to other pages are obviously out of the Servlet context, so the glassfish returns the 404 error.

Instead of using getRequestDispatcher (), I have already tried to use the response.sendRedirect ("pages / server_server.jsp") , in that case I can enter the data and access the internal links, but the no javascript alert is displayed.

Anyone who has ever had this situation would have any suggestions?

Thank you all!

    
asked by anonymous 09.05.2015 / 17:23

1 answer

1

Although your approach is working, elá is far out of the way. An alternative and more interesting way would be to set the alert to your JSP page and only display it if it passed the condition that the data was entered successfully.

In your JSP , it would look something like this:

<script>

document.onload = function() {

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

};

</script>

Now, in 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 you would commonly use is request.setAttribute() , however, you will not have access to request when using sendRedirect() for the response. Soon you will have to use session since it is persistent among many requests.

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

    
24.10.2016 / 18:28