1. 程式人生 > >java系統高併發的解決方案

java系統高併發的解決方案

package com.jb.y2t034.thefifth.web.servlet;  
import java.io.ByteArrayOutputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.OutputStreamWriter;  
import java.io.PrintWriter;  
import javax.servlet.RequestDispatcher;  
import javax.servlet.ServletContext;  
import javax.servlet.ServletException;  
import javax.servlet.ServletOutputStream;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpServletResponseWrapper;  
/** 
* 建立HTML靜態頁面 
* 功能:建立HTML靜態頁面 
* 時間:2009年1011日 
* 地點:home 
* @author mavk 

*/  
public class CreateStaticHTMLPage {  
    /** 
     * 生成靜態HTML頁面的方法 
     * @param request 請求物件 
     * @param response 響應物件 
     * @param servletContext Servlet上下文 
     * @param fileName 檔名稱 
     * @param fileFullPath 檔案完整路徑 
     * @param jspPath 需要生成靜態檔案的JSP路徑(相對即可) 
     * @throws IOException 
     * @throws ServletException 
     */  
    public void createStaticHTMLPage(HttpServletRequest request, HttpServletResponse response,ServletContext servletContext,String fileName,String fileFullPath,String jspPath) throws ServletException, IOException{  
        response.setContentType("text/html;charset=gb2312");//設定HTML結果流編碼(即HTML檔案編碼)   
        RequestDispatcher rd = servletContext.getRequestDispatcher(jspPath);//得到JSP資源   
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();//用於從ServletOutputStream中接收資源   
        final ServletOutputStream servletOuputStream = new ServletOutputStream(){//用於從HttpServletResponse中接收資源   
            public void write(byte[] b, int off,int len){  
                byteArrayOutputStream.write(b, off, len);  
            }  
            public void write(int b){  
                byteArrayOutputStream.write(b);  
            }  
        };  
        final PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(byteArrayOutputStream));//把轉換位元組流轉換成字元流   
        HttpServletResponse httpServletResponse = new HttpServletResponseWrapper(response){//用於從response獲取結果流資源(重寫了兩個方法)   
            public ServletOutputStream getOutputStream(){  
                return servletOuputStream;  
            }  
            public PrintWriter getWriter(){  
                return printWriter;  
            }  
        };  
        rd.include(request, httpServletResponse);//傳送結果流   
        printWriter.flush();//重新整理緩衝區,把緩衝區的資料輸出   
        FileOutputStream fileOutputStream = new FileOutputStream(fileFullPath);  
        byteArrayOutputStream.writeTo(fileOutputStream);//把byteArrayOuputStream中的資源全部寫入到fileOuputStream中   
        fileOutputStream.close();//關閉輸出流,並釋放相關資源   
        response.sendRedirect(fileName);//傳送指定檔案流到客戶端   
    }