Servlet3.0异步阻塞了,求解

rgone 发布于 2013/08/14 16:09
阅读 251
收藏 0

Servlet3.0异步阻塞了,求解!原先准备当页面提交到CreateIISSites.htm时使用var timeoutID = setTimeout("findreporter()",1000);来轮询服务端的isCompleted()方法,把时间打印到页面。

但实际运行的情况是提交到CreateIISSites.htm后,总会等待异步线程运行完JavaScript才会去调用isCompleted()方法,把时间打印到页面上。

客户端代码:


<script type="text/javascript"> 
	
    function findreporter(){ 
       // alert("确定要在以上服务器上创建站点吗?"); 
       // document.getElementById("updateButton").disabled = "disabled";
        var url = "/CreateIISSites.htm?method=isCompleted"; 
        if (window.XMLHttpRequest) { 
          req = new XMLHttpRequest(); 
        }else if (window.ActiveXObject) { 
          req = new ActiveXObject("Microsoft.XMLHTTP"); 
        } 
        if(req){ 
          req.open("GET",url, true); 
          req.onreadystatechange = checkcontent; 
          req.send(null); 
        } 
   		}
var timeoutID = setTimeout("findreporter()",1000);
    function checkcontent(){ 
    if (req.readyState == 4) { // 判断对象状态 
     if (req.status == 200) { // 信息已经成功返回,开始处理信息 
          if(req.responseText != ""){ 
            if(req.responseText!=""){ 
            
            	var returnValue2=req.responseText.split(":"); 
				if( returnValue2[2] == "10" ){ 
				cleartimeout(timeoutID);
				document.getElementById("createsitesprocess").innerHTML=req.responseText+"所以站点创建完毕,停止状态获取!";
				}else{
				var timeoutID = setTimeout("findreporter()",1000);
				
				}
				
              var returnValue=req.responseText.split(":"); 
              
              //alert(req.responseText); 
              //document.getElementById("createsitesprocess").innerHTML=req.responseText;
              document.getElementById("createsitesprocess").innerHTML=req.responseText;
              document.getElementById('reporterUserName').value="username"; 
              document.getElementById('reporterUserTel').value=""; 
              if(returnValue[0] && returnValue[0]!="_") 
                document.getElementById('reporterUserName').value=returnValue[0]; 
              if(returnValue[1] && returnValue[1] != "null" ){ 

                document.getElementById('reporterUserTel').value=returnValue[1]; 
              } 
              
              
              

              

            } 
          }else{ 
            document.getElementById('reporterUserName').value=""; 
            document.getElementById('reporterUserTel').value=""; 
          } 
     } else {//页面不正常 
         alert("您所请求的页面有异常。"); 
     } 
    }
    } 
</script> 
<div id="createsitesprocess"></div>


服务端代码:


package com.dengdie.opt.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import com.dengdie.opt.util.DataBaseConnection;
import com.dengdie.opt.util.MyCountDown;
import com.dengdie.opt.workthread.CreateIISSitesThread;
import java.util.Date;
import java.text.SimpleDateFormat;

@WebServlet(name="CreateIISSites",urlPatterns="/CreateIISSites.htm",asyncSupported=true)
public class CreateIISSites extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    public CreateIISSites() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		isCompleted(request, response);
	}

	protected void isCompleted(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Date now = new Date(); 
		SimpleDateFormat dateFormat = new SimpleDateFormat("HH🇲🇲ss");//可以方便地修改日期格式
		response.getWriter().write(dateFormat.format(now));
		System.out.println("isCompleted方法被调用"+ dateFormat.format( now ));	
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 接收参数
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String privateIpAddress = request.getParameter("privateIpAddress");
	
		response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
		// 将list赋值到velocity模版中,由模版输出到客户端
		Properties p = new Properties();
		p.setProperty("resource.loader", "class");
		p.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		//设置资源加载器器为ClasspathResourceLoader,这段可以写到配置文件中
		VelocityEngine ve = new VelocityEngine();
		ve.init(p);
		Template template = ve.getTemplate("/templates/result/CreateIISSites.vm", "UTF-8");
		//取得velocity的上下文context
        VelocityContext context = new VelocityContext();
        //把数据填入上下文
        context.put("title", privateIpAddress+"-服务列表");//设置此页标题
        //输出流
        StringWriter writer = new StringWriter();
        //转换输出
        template.merge(context, writer);
        //writer.flush();
        response.getWriter().println(writer.toString());
        
        out.flush();
       
        HttpSession session = request.getSession();

		// 接收参数
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String sitename = request.getParameter("sitename");
		String siteport = request.getParameter("siteport");
		String sitepath = request.getParameter("sitepath");
		String siteversion = request.getParameter("siteversion");
		String serverlist = request.getParameter("serverlist");
		String userName = (String)session.getAttribute("username");
		
		String[] ary = serverlist.split("\n");
		

		//获取脚本文件路径
		DataBaseConnection dataBaseConnection = new DataBaseConnection();
		String dataBaseConfigForWrite[] = new String[4];
		dataBaseConfigForWrite = dataBaseConnection.loadDataConfig();
             
        //进入异步模式,调用业务处理线程进行业务处理
        //Servlet不会被阻塞,而是直接往下执行
        AsyncContext asyncContext = request.startAsync();
		CreateIISSitesThread createIISSitesThread = new CreateIISSitesThread(sitepath, sitename, siteversion,siteport,ary,userName,dataBaseConfigForWrite[3],asyncContext);
        Thread thread = new Thread(createIISSitesThread);
        asyncContext.start(createIISSitesThread);
		}
	}


加载中
0
rgone
rgone

怎么有的浏览器提交后就可以刷新显示时间,有的浏览器非要等异步线程执行完毕后才刷新时间。

同种浏览器不同机器都反应不一样,崩溃!

返回顶部
顶部