본문 바로가기

JSP/Learn

[JSP] 서블릿으로 다운로드 페이지 구현

JSP로 다운로드를 구현하는걸 이리저리 공부하다가 찾게된 페이지

http://www.jspwiki.org/wiki/Main 

 이걸 왜 아직까지 몰랐었을까;;;;
이곳에 서블릿으로 다운로드 구현하는 방법이 꽤 깔끔하게 나와있다.
http://www.jspwiki.org/wiki/MakingADownloadServlet 

 
중요한건 
resp.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + "\"" ); 

헤더를 설정 해 주는 것과

ServletOutputStream op       = resp.getOutputStream();
서블릿 아웃풋 스트림을 정의 해 주는 것.
 

그러나 한가지 주의 해야 할것은
JSP페이지는 기본적으로 outputstream이 out이란 객체에 정의가 되어 있다
그렇기에 JSP에서 새로 outputstream을 생성하면 다음과 같은 오류가 난다.

심각: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response

이를 해결하기 위해선 본래 기본으로 가지고 있던 out 객체르 비워주고, 새로운 객체를 선언해야 한다

    out.clear(); //out--> jsp자체 객체
    out=pageContext.pushBody(); //out--> jsp자체 객체
    //getOutputStream() has already been called for this response 해결

 이렇게 코딩을 해주면 위의 오류가 발생하지 않는다.


사실 다운로드 구현을 하려면 JSP페이지가 아닌 서블릿에서 다운로드를 구현하는게 맞다고 본다.