I need to write a HTTP server program in Java that
- Process SOME requests (i.e, having certain parameters) to store some data sent from clients, and.
- The rest of requests show a "home" page, showing the data received from the clients.
The problem is, in the "home" page I want to show a page that uses local images or JavaScript, and I don't know how to make it work. I mean, I have seen the example in NanoHTTPD home page and it works great, but where should I place the static content (images, js) to be included in the HTML I generate as a response?
Code added as per request.
@nicomp, this example is an adaptation from the example code in https://github.com/NanoHttpd/nanohttpd. The image monkey.png is not served (it appears as a broken img in the browser).
public class Main extends NanoHTTPD {
public Main() throws IOException {
super(8080);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
System.out.println("\nRunning! Point your browsers to http://localhost:8080/ \n");
}
public static void main(String[] args) {
try {
new Main();
} catch (IOException ioe) {
System.err.println("Couldn't start server:\n" + ioe);
}
}
@Override
public Response serve(IHTTPSession session) {
String msg = "<html><body><h1>Hello server</h1>\n";
msg += "<img src=\"monkey.png\">";
return newFixedLengthResponse(msg + "</body></html>\n");
}
}
To include static content such as images and JavaScript in the HTML response, you can create a directory within your project to store these files. Let's call it
static.Next, you need to serve the static content files from this directory. You can do this by creating a
StaticFileServerclass that extends theNanoHTTPDclass and overrides theserve()method. In theserve()method, you can check if the requested URI starts with the string "/static" and if so, serve the corresponding file from thestaticdirectory. Here's an example:In the
serve()method, we check if the URI starts with "/static". If it does, we construct the file path by removing the "/static" prefix and appending it to thestaticDirpath. Then we open an input stream to read the file and return aChunkedResponsewith the file's MIME type. If the file is not found, we return a 404 Not Found response.Now that we have our
StaticFileServerclass, we can use it to serve our static files. In your main HTTP server program, you can create an instance of theStaticFileServerclass and pass in the port and the path to thestaticdirectory. Then, in theserve()method of your main HTTP server program, you can generate the HTML response and include references to the static files using their URLs: