0

我有两个jsp 页面和一个servlet。当我提交我的 page1.jsp 时,servlet 会做一些繁重的工作,并在完成工作后重定向到 page2.jsp。当 servlet 完成它的工作时,我想显示一个加载图像。

我尝试使用 ajax 但它不显示图像这里是代码。

page1.jsp

<html>
<head>
    <script>
       function image(){
           var xmlhttp;
           if (window.XMLHttpRequest)
            {
                xmlhttp = new XMLHttpRequest();
            }
            else
            {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function()
            {
                if (xmlhttp.readyState === 4)
                {
                    document.getElementById("newdiv").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", "test.jsp", true);
            xmlhttp.send();            
       }
    </script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>

    <div id="newdiv">
    <form id="form1" action="loading" method="post" onsubmit="image()">
         <h1>execute thread</h1>
        <input id="abc" type="submit" name="submit" value="submit"/>           
    </form>
    </div>
</body>
</html>

测试.jsp

<html>
<head>      
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>

    <div id="newdiv">
        <h1>Hello World!</h1>
      <img id="loading" src="images/ajax_loader.gif" style="display: block; height: 50px; width: 50px;" />
    </div>
</body>
</html>

请帮忙。

PS:我不想用jquery

4

1 回答 1

-1

你的解决方案在这里

不要在 page2.jsp 中指定加载图像,在 servlet 本身中指定。例子:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 /**
 *
 * @author Ganesh
 */
@WebServlet(name = "NewServlet", urlPatterns = {"/NewServlet"})
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {

        for(int i=0;i<=10000000;i++)
        {
        out.println("<img id=loading src=images/loading.gif style=display: block; height: 50px; width: 50px; >");

        }
        response.sendRedirect("page2.jsp");
    } finally {            
        out.close();
    }
}
于 2013-06-17T07:01:36.503 回答