簡短回答:創建一個servlet,知道從哪裏獲取這些文件並讓它爲它們服務。
較長版本/說明:
創建servlet,映射它例如/yourapp/pdfs/*
:
@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>