본문 바로가기

Job/Java

[Jsp] 다운로드 페이지 만들기 NIO 버젼

■ 프로세스

1) 커널 영역 버퍼에서 프로세스 영역 안의 버퍼로 데이터를 복사하는 비효율적인 과정

    => 커널 영역의 버퍼에 저장된 데이터를 직접 사용하여 복사하는 시간을 단축 시킴

 

2) 디스크 컨트롤러에서 커널 영역의 버퍼로 데이터를 복사하는 동안 프로세스 영역은

    blocking.

    => 유저영역의 버퍼를 사용하지 않아 Non blocking 으로 서버에 과부하 를 줄임

 

※ IO package BufferedInputStream, BufferedOutputStream

   => NIO package FileChannel, WritableByteChannel 으로 변경

 

■ SRC

<%@ page contentType="application;" import="java.net.*,java.io.*,java.nio.channels.*" %>
<%
 String filename = request.getParameter("FLNM");
 String svFilename = request.getParameter("FLSVNM");
 String filepath = request.getParameter("FLPTHNM"); 

 File file = new File(filepath+svFilename);

    try{

  String agent = request.getHeader("User-Agent");  
  
  if (agent.indexOf("MSIE 6.0") > -1 || agent.indexOf("MSIE 5.5") > -1) {  
   response.setHeader("Content-type", "application/octet-stream");
   response.setHeader("Content-Disposition", "attachment; filename=" + filename);
   response.setHeader("Content-Transfer-Encoding", "binary");
  }  
  else
  {
   response.setHeader("Content-type", "file/unknown");
   response.setHeader("Content-Disposition", "attachment; filename=" + filename);
   response.setHeader("Content-Description", "Servlet Generated Data");
  }
  
  response.setHeader("Pragma", "no-cache");
  response.setHeader("Cache-Control", "private");
  response.setHeader("Expires", "0");  
  
    }catch(Exception e1){
  e1.printStackTrace();
    }

 FileInputStream fis = null;
 FileChannel in = null;
 WritableByteChannel outs = null;

 try{
  if (file.isFile()) {  
   fis = new FileInputStream(file);
   in = fis.getChannel();
   outs = Channels.newChannel(response.getOutputStream()); 
   
   in.transferTo(0,in.size(),outs);
     
   outs.close();
   in.close();
   fis.close(); 
  }
 } catch(FileNotFoundException e4) { 
  e4.printStackTrace();
 } catch(IOException e3) {
  e3.printStackTrace();
 } catch(Exception e2) { 
  e2.printStackTrace();
 } finally {

  if(outs != null) {
   try { outs.close(); } catch(Exception f1) {}
  }
  if(in != null) {
   try { in.close(); } catch(Exception f2) {}
  }
  if(fis != null) {
   try { fis.close(); } catch(Exception f3) {}
  } 
 }
%>