1. 程式人生 > >servlet檔案非同步下載

servlet檔案非同步下載

  1. web配置:

    web.xml的所有servlet和filter新增配置項: <async-supported>true</async-supported>

  2. java服務端響應:

    HttpServlet實現:
    
    private ExecutorService executorPool=Executors.newFixedThreadPool(20);
    
    protectedvoid doPost(HttpServletRequest request,
    			HttpServletResponse response) 
    {
    AsyncContext ctx=request.startAsync();//開啟非同步處理
    ctx.setTimeout(5000);
    executorPool.submit(new AsyncRequestDownloadService(faceCloudService,downloadBean,ctx)); // 使用執行緒池控制呼叫
    }
    
    
    ---------------------------------------》
    
    public class AsyncRequestDownloadService implements Runnable{
    
    	private AsyncContext ctx;
    	private DownloadBean downloadBean;
    	private BusinessService businessService;
    	
    	public AsyncRequestDownloadService(BusinessService businessService,DownloadBean downloadBean,AsyncContext ctx ){
    		super();
    		this.businessService=businessService;
    		this.ctx = ctx;
    		this.downloadBean=downloadBean;
    	}
    	
    	@Override
    	public void run() {
    		downloadFile(downloadBean,(HttpServletResponse)ctx.getResponse());
    		ctx.complete();
    	}
    
    	private void downloadFile(DownloadBean downloadBean,HttpServletResponse response) {
    		switch (downloadBean.getBusinessType()) {
                // TODO
    		}
    	}