在ajax中调用java方法

我在Netbeans Ide中创建了一个jsp应用程序。 我在调用ajax中的java类方法时遇到问题。是否可以这样做

我的java类是这样的:

public class Hello { public String execute(String s) { return "success"; } } 

我无法弄清楚如何使用ajax调用execute方法:我当前的ajax代码是:

 var val="test string"; $.ajax({ type: "GET", url: "http://localhost:8084/Shade/src/java/mail/Main.execute", data: val, async: true, cache: false, success: function (msg) { alert("hi"); $(".col-1").html(msg); }); 

提前Thanx 🙂

AJAXAsynchronous JavaScript And XML的首字母缩写。 它提供了异步与服务器通信的能力。

为了解释这一点,您可以向服务器发送请求并继续与用户进行用户交互。 您无需等待服务器的响应。 一旦响应到达,UI中的指定区域将自行更新并反映响应信息。 整页不需要重新加载。

因此,您无法直接访问Java类作为url来发出Ajax请求。 它应该是任何映射的URL,如JSPServletsPHP等。

创建一个JSP(例如hello.jsp

 <% String strResponse; mail.Main objMain = new mail.Main(); strResponse = objMain.execute(); %> <%=strResponse %> 

在Ajax请求中

 url: "hello.jsp", 

编辑:添加示例:

   

在Servlet / JSP中访问你的参数request.getParameter("uName");

您无法直接调用该方法。 您应该将URL映射到要调用的方法。 这可以在servlet中完成。 如果您已经通过Java代码提供页面,则只需添加一种新方法来为包含所需内容的页面提供服务。