简体   繁体   中英

Redirecting the page with Servlets Java

I have a page with a form that when it's submitted goes to a that inserts the form data into the database. 页面,提交该表单后,该页面将转到 ,该将表单数据插入数据库。

When the data is inserted into the database, I'm trying to get the browser back to my jsp page and show a javascript alert saying that the data was inserted successfully, my code is the following:

    RequestDispatcher rd;
    if(dao.insertClient(client)) { 
        rd = getServletContext().getRequestDispatcher("/pages/clients.jsp");
        rd.include(request, response);
        out.print(
            "<script type=\"text/javascript\">"
                + "alert("Client inserted successfully!");"+
            "</script>"
        );           
    }

This code is doing exactly what I want, but this method redirects the page to the servlet itself, and the URL is like http://localhost:8080/Servlet , this way I access any intern link of the page, since the links to the other pages obviously are outside of the servlet context, and the glassfish returns the 404 error. 将页面重定向到servlet本身,而URL就像http:// localhost:8080 / Servlet一样 ,这样我访问该对象的任何内部链接。页面,因为到其他页面的链接显然在servlet上下文之外,并且glassfish返回404错误。

Instead of using getRequestDispatcher(), I've tried using the , this way I can insert the data into the database and access the intern links, but the javascript alert shown. 而不是使用getRequestDispatcher(),通过这种方式,我可以将数据插入数据库并访问内部链接,但是显示javascript警报。

Somebody has a suggestion on how I can redirect the page to the and display the javascript alert? 并显示javascript警报提出了建议。

Thanks!

you can try another approach :

Set parameter from servlet like this :

RequestDispatcher rd;
if(dao.insertClient(client)) { 
     rd = getServletContext().getRequestDispatcher("/pages/clients.jsp");
     request.setAttribute("isSuccess", "success");
     rd.include(request, response);
}

access the parameter in jsp to check whether to show alert or not.

<%
   String result = request.getParameter("isSucess");
   if("success".equals(result)){
%>
   <script type="text/javascript" >
      alert("Client inserted successfully!");
   </script>
<%
  }
%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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