47 lines
1.5 KiB
Java
47 lines
1.5 KiB
Java
package ctbrec.servlet;
|
|
import java.io.FileNotFoundException;
|
|
import java.io.IOException;
|
|
import java.io.InputStream;
|
|
import java.io.OutputStream;
|
|
import java.net.URLConnection;
|
|
|
|
import javax.servlet.ServletException;
|
|
import javax.servlet.http.HttpServlet;
|
|
import javax.servlet.http.HttpServletRequest;
|
|
import javax.servlet.http.HttpServletResponse;
|
|
|
|
public class StaticFileServlet extends HttpServlet {
|
|
|
|
private String classPathRoot;
|
|
|
|
public StaticFileServlet(String classPathRoot) {
|
|
this.classPathRoot = classPathRoot;
|
|
}
|
|
|
|
@Override
|
|
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
|
String request = req.getRequestURI();
|
|
serveFile(request, resp);
|
|
}
|
|
|
|
@Override
|
|
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
|
doGet(req, resp);
|
|
}
|
|
|
|
private void serveFile(String resource, HttpServletResponse resp) throws IOException {
|
|
InputStream resourceAsStream = getClass().getResourceAsStream(classPathRoot + resource);
|
|
if (resourceAsStream == null) {
|
|
throw new FileNotFoundException();
|
|
}
|
|
resp.setContentType(URLConnection.guessContentTypeFromName(resource));
|
|
resp.setStatus(HttpServletResponse.SC_OK);
|
|
OutputStream out = resp.getOutputStream();
|
|
int length = 0;
|
|
byte[] buffer = new byte[1024];
|
|
while ((length = resourceAsStream.read(buffer)) >= 0) {
|
|
out.write(buffer, 0, length);
|
|
}
|
|
}
|
|
}
|