【问题标题】:Calling a java method from web page to generate a Processing sketch and display this sketch on the web page从网页调用 java 方法以生成处理草图并在网页上显示此草图
【发布时间】:2020-01-30 09:51:37
【问题描述】:

我在 Eclipse 中编写了一个处理程序,它生成图像并将其保存到我计算机上的特定位置。

有没有什么方法可以从 javascript 文件中运行这个程序,这样当用户点击网页上的按钮时,会调用 Processing 程序中的相应方法,生成图像并最终将图像显示在网页。

我在这方面没有太多经验,但我想我可以让 Processing 方法在图像保存后发出 POST 请求,以便将其发送到相关服务器?

我在这里遇到的主要问题是如何从网页实际调用该方法。使用 Processing.js 或将我的 java 代码转换为 javascript 并不是一个真正的选择,因为我需要将 ANTLR 导入到我的处理程序中,据我所知只能与 Java 一起使用。

为了清楚我的程序是一个.java 文件,它通过导入processing.core 以处理草图的形式生成图像。

我乐于学习新技术等。

非常感谢任何帮助。

【问题讨论】:

    标签: javascript eclipse processing web-deployment


    【解决方案1】:

    您需要在 JavaScript 中调用一个 HTTP 请求,该请求将在您的后端触发一个函数。这可以通过Fetch API 来实现,它是一个获取和发送资源的接口。

    由于您无法在 Web 上运行 Java,因此您需要依赖 JavaScript 客户端和 Java 服务器之间的某种形式的通信。您可以来回发送数据以更新两端。

    下面我创建了一些例子来说明这对你的影响。你有你的按钮,与服务器对话的函数和每当点击按钮时触发的事件监听器,将按钮连接到函数。

    <!-- Create a button in html -->
    <button class="process">Process me</button>
    
    // Write a function that sends a HTTP request to your server.
    // Can be either POST or GET. Change the 'yoururl' part to your own endpoint.
    // The rest of the function will check if the request has been successful and 
    // returns a string with the received data from the server, if there is any.
    function process() {
      return fetch('yoururl/process', {
        method: 'POST',
      }).then(response => {
        if (response.status === 200) {
          return response.text();
        }
      }).catch(error => {
        console.log(error);
      });
    }
    
    // Select the button from the HTML.
    const button = document.querySelector('.process');
    
    // Fire a function when the button is clicked.
    button.addEventListener('click', function(event) {
      process().then(text => {
        console.log(text); // Show the text that has been received from the server.
      });
    });
    

    但是您的问题没有明确的答案,因为它非常广泛。我希望这至少能让你在它如何工作方面找到正确的方向。

    【讨论】:

      猜你喜欢
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多