짧은 대답 : 해당 파일을 가져올 위치를 알고 서 전달할 수있는 서블릿을 만듭니다.
더 긴 버전/설명 :
는 서블릿을 작성 가령에 매핑 /yourapp/pdfs/*
: 위의 코드는 일부 조정을 beed 수 있지만 일반적으로이 솔루션을 설명
@WebServlet("/pdfs/*")
public class PdfServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) {
String basePath = getServletContext().getInitParameter("basePath");
File f = new File(basePath + File.separator + req.getPathInfo());
/////////////////////////////////////////////////////////////////////
//// BIG WARNING: ////
//// Normalize the path of the file and check if the user can ////
//// legitimately access it, or you created a BIG security ////
//// hole! If possible enhance it with system-level security, ////
//// i.e. the user running the application server can access ////
//// files only in the basePath and application server dirs. ////
/////////////////////////////////////////////////////////////////////
if(f.exists()) {
OutputStream out = res.getOutputStream();
// also set response headers for correct content type
// or even cache headers, if you so desire
byte[] buf = new byte[1024];
int r;
try(FileInputStream fis = new FileInputStream(f)) {
while((r=fis.read(buf)) >= 0) {
out.write(buf, 0, r);
}
}
}
else res.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
...
지금
web.xml
에서 컨텍스트 초기화 파라미터 지정
<context-param>
<param-name>basePath</param-name>
<param-value>/the/path/to/the/pdfs</param-value>
</context-param>
을