NanoHTTPD如何从app呈现变量

时间:2015-02-05 10:49:12

标签: java dynamic webpage nanohttpd

我基于它玩NanoHTTPD和WebServer。要更新我的代码(应用程序)中的任何对象,我可以使用GET / POST方法。但是我怎样才能创建动态页面?例如,我在光盘上有html页面,它应该显示当前温度:

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

  <body>

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

  </body>

</html>

如何将基于NanoHTTPD的应用程序中的“变温”传递给html文件并将其显示在浏览器中?

1 个答案:

答案 0 :(得分:2)

您必须从磁盘中读取模板,并将[temperature variable]子字符串替换为您要包含的值。

要阅读该文件,您可以使用Files类:

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

插入温度:

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

最后将此作为NanoHTTPD的响应发送:

return new NanoHTTPD.Response(html);

完整的计划:

前言:不处理异常,这仅用于演示目的。

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);
    }
}

有关更多高级示例,请查看NanoHttpd Github网站的Samples package