I have two applications: (1) a JavaFX application A and (2) a purely JavaScript web application B (no backend) accessed either as local files (for developers) or at a certain URL (for the users).
In A the user can save a file and then open B in the user's browser via Desktop.getDesktop().browse()
. Then the user can load that file in B by clicking on an input
element of type file
, which allows the usage of FileReader
.
That process is too cumbersome for the users, so I want to remove that requirement of the user to save and load a file.
My problem is: How can I transfer this data from A to B now?
FileReader
cannot read files using path names because of security Is there any way to get one of the above methods to work or is there any alternative to pass data between Java and a purely client-based JavaScript application in a browser?
As suggested in the accepted answer, I serve the data as using Jetty.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.json.JSONArray;
public class JsonServer extends Server
{
static final int PORT = 1234;
public JsonServer(JSONArray json)
{
super(PORT);
setHandler(new JsonHandler(json));
}
public static class JsonHandler extends AbstractHandler
{
final JSONArray json;
public JsonHandler(JSONArray json)
{
this.json = json;
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("application/json; charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
try(PrintWriter out = response.getWriter();)
{
out.println(json);
}
baseRequest.setHandled(true);
}
}
}
Server server = new JsonServer(json);
server.start();
browse("https://myapp.com?load=http://localhost:1234");
const load = url.searchParams.get("load");
const json = await (await fetch(load)).json();
如果您假设网页总是在运行 JavaFX 应用程序的同一台机器上查看,您可以始终让它通过 HTTP(使用Jetty或类似)导出文件,然后让网页使用URL,例如“ http://localhost:port/fileContainingData ”。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.