日期:2014-05-17  浏览次数:20646 次

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

------解决方案--------------------
Java code

/*写了个简单的线程处理*/
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();
    }

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