How to call Java methods from javascript using ajax?

梦想与她 提交于 2019-12-02 17:12:32

问题


I have a webpage where I have a button. What I want to achieve is whenever I click on this button , it should call a java method named getMessage() which is present inside a java program. After calling this method it displays a greeting on the screen. I read that calling java functions from javascript is not a good idea. That's why I am trying to achieve above effect using ajax.

My html file : index.html =>

<!doctype html>
<html>
<head>
<meta charset="utf-8"/>

<script language="javascript">   

      function openMsg()
   {          
     var msg = //code that makes a call to getMessage() from a java file and returns the response say "Good Morning..! "  
     document.getElementById("print").innerHTML = msg;
   }       

  </script> 
  </head>

  <body>
     <button onclick="openMsg();">Click to open message</button>
     <p id="print"></p>
  </body>
</html>

My java file : Example.java =>

 import java.awt.Color;
 import java.awt.Graphics;

 import javax.swing.JApplet;

 public class Example extends JApplet{

     public void start()    
   {

   }

     public void init() 
   {
      setBackground(Color.blue);
   }

     public void paint(Graphics g)  
   {
      g.drawString("Hello World !", 100, 100);
   }

     public void getMessage()
   {
     System.out.println("Good Morning..!!!");
   }

  }

Please help me...

来源:https://stackoverflow.com/questions/40104912/how-to-call-java-methods-from-javascript-using-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!