Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A servlet returning index.html and bundle.js
public class ReactServlet extends HttpServlet {
private static final long serialVersionUID = 250817058831319271L;
// The paths used to serve index.html
private final List<String> routes = Arrays.asList("/", "/counter", "/about");
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
String pathInfo = request.getPathInfo();
try {
if (pathInfo == null) {
// Browsers won't redirect to bundle.js if the servlet path doesn't end with a "/"
addSlashToServletPath(request, response);
return;
}
String resource = findResourceFromPathInfo(pathInfo);
String contentType = guessContentTypeFromResourceName(resource);
response.setContentType(contentType);
try(ServletOutputStream responseBody = response.getOutputStream()) {
try(InputStream resourceFromClasspath = getClass().getClassLoader().getResourceAsStream(resource)) {
if (resourceFromClasspath != null) {
copyStream(resourceFromClasspath, responseBody);
response.setStatus(200);
return;
}
String message = String.format("Resource \"%s\" not found on the classpath", resource);
response.sendError(404, message);
}
}
} catch (IOException e) {
response.setStatus(500); // Report internal server error
}
}
String guessContentTypeFromResourceName(String resource) {
String contentType = URLConnection.guessContentTypeFromName(resource);
if (contentType != null) {
return contentType;
}
String extension = resource.substring(resource.lastIndexOf('.') + 1);
if ("xhtml".equals(extension)) {
return "text/html";
}
if ("js".equals(extension)) {
return "application/javascript";
}
if ("css".equals(extension)) {
return "text/css";
}
return null;
}
private String findResourceFromPathInfo(String pathInfo) {
if (routes.contains(pathInfo)) {
return "index.xhtml";
}
return pathInfo;
}
private void addSlashToServletPath(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendRedirect(String.format("%s/", request.getServletPath()));
}
private void copyStream(InputStream input, ServletOutputStream output) throws IOException {
int c;
while((c = input.read()) != -1) {
output.write(c);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment