Search code examples
javadynamichtmlnanohttpd

NanoHTTPD how to present variable from app


I play NanoHTTPD and WebServer based on it. To update any object in my code (application) I can use GET/POST method. But how can I create dynamic pages? For example I have html page on disc and it should present current temperature:

<html>
  <head>
    <title>My page</title>
  </head>

  <body>

    <p style="text-align: center">Temperature: [temperature variable] </p>

  </body>

</html>

How can I pass "variable temperature" from my application based on NanoHTTPD to html file and present it in browser?


Solution

  • You have to read the template from your disk, and replace the [temperature variable] substring with the value you want to include.

    To read the file, you can use the Files class:

    byte[] data = Files.readAllBytes(Paths.get("mytemplpate.html"));
    String templ = new String(data, StandardCharsets.UTF_8);
    

    To insert your temperature:

    double temperature = 22.3;
    String html = templ.replace("[temperature variable]", Double.toString(temperature));
    

    And finally to send this as the response with NanoHTTPD:

    return new NanoHTTPD.Response(html);
    

    The complete program:

    Foreword: Exceptions are not handled, this is just for demonstration purposes.

    public class TemperatureServer extends NanoHTTPD {
        // Loaded and cached html template
        private static String templ;
    
        // Value of this variable will be included and sent in the response
        private static double temperature;
    
        public TemperatureServer () {
            super(8080);
        }
    
        @Override
        public Response serve(IHTTPSession session) {
            String html = templ.replace("[temperature variable]",
                Double.toString(temperature));
            return new NanoHTTPD.Response(html);
        }
    
        public static void main(String[] args) throws Exception {
            byte[] data = Files.readAllBytes(Paths.get("mytemplpate.html"));
            templ = new String(data, StandardCharsets.UTF_8);
    
            ServerRunner.run(TemperatureServer.class);
        }
    }
    

    For more advanced examples check out the Samples package of the NanoHttpd Github site.