jsp+servlet,点击一个button,后台执行一个shell,用的是Runtime.getRuntime().exec()方法,执行shell的时候会随时返回命令行结果到前台页面用out=response.getWriter打印,怎么能实现同步把结果刷新显示的页面上,现在是只能等到shell进程都结束后才能显示

解决方案 »

  1.   

    Servlet中的代码如下,就是想让out.println的东西即时打印到jsp页面上,现在是必须等到进程执行结束之后才能统一打印,我想实时打印
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String country = request.getParameter("countrylist");
    String shellpath = path + shellname;
    String shellstring = "sh" + " " + shellpath + " " + country;
    logger.info("Shellstring:" + shellstring);
    BufferedReader bufferedreader = null;
    out = response.getWriter();
    out.println("==========Monitor www.rhapsody.com task start up!==========");
    try {
    Process process = Runtime.getRuntime().exec(shellstring);
    if(process != null){
    bufferedreader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    int exitValue = process.waitFor();
    if(0 != exitValue){
    out.println("Call shell failed. error code is :" + exitValue);
    }
    }else{
    out.println("Call shell script failed.");
    }
    String line = "";
    while ((line = bufferedreader.readLine()) != null){
    out.println(line);
    }

    bufferedreader.close();

    } catch (InterruptedException e) {
    e.printStackTrace();
    } catch (Throwable e) {
    e.printStackTrace();
    }
    out.println("==========Monitor www.rhapsody.com task Complete!==========");
    out.flush();
    out.close();
    }
      

  2.   

    要是用多线程实现呢,谁能给贴个代码,就是在shell脚本执行期间,实时打印out.println()的内容
      

  3.   


    /*写了个简单的线程处理*/
    public static void output(final InputStream in, final ServletOutputStream out){
     new Thread(){
     public void run(){
     byte[] buf = new byte[1024];
     int n=0;
     try{
     while((n=in.read(buf))!=-1){
     out.write(buf, 0, n);
     }
     }catch(Exception e){
     e.printStackTrace();
     }finally{
     try {
    in.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
     try {
    out.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
     }
     }
     }.start();
    }
      

  4.   

     out.write一行后就out.flush()一下,这样在页面就会输出write的内容的
      

  5.   

    可以用dwr3的反向ajax技术主动向页面推送消息
      

  6.   

    out.print()后面立即flush()出去,行不??