我有一个java应用程序,它报告几个网站的up / down状态,并使用数据创建一个.json文件。我有一个HTML页面,它使用javascript来获取.json文件,并显示一个漂亮的小网格,红色或绿色的灯光告诉你网站是上升还是下降。我有不知道如何使java应用程序告诉html页面确切地命名了.json文件(我在每个应用程序运行时创建一个新的带时间戳的.json文件)。是否有任何方法可以在加载时将参数或其他内容传递给HTML页面(当前使用Desktop.getDesktop().browse(URI.create("file://blah");
),还是每次运行应用程序时都会覆盖我的.json文件?
答案 0 :(得分:0)
如何使用查询参数?与file://blah.html?json=foo.json
或片段一样:file://blah.html#foo.json
。
答案 1 :(得分:0)
您可以创建一个小型本地服务器并将url / json注册到您想要的任何文件:
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class main {
static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/", new IndexHandler());
server.createContext("/json", new JsonHandler());
server.start();
}
static class IndexHandler implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
String response = readFile("index.html", StandardCharsets.UTF_8);
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
static class JsonHandler implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
String response = readFile("whatEverJsonYouWant.json", StandardCharsets.UTF_8);
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
现在可以将JS更改为fetch / json