简体   繁体   English

从JavaScript代码调用Java函数?

[英]Calling a Java Function From JavaScript Code?

Ok, maybe this is a very common question, but I can't find a right answer... 好的,也许这是一个非常普遍的问题,但是我找不到正确的答案...
I have a function in Java (actually, is a Servlet) and what I need/trying to do is this: 我有一个Java函数(实际上是一个Servlet),我需要/尝试做的是:
After doing some things, I need to show a "confirm" window, before doing some other things in my code... I'm doing this through javascript, of this way: 做完一些事情之后,我需要显示一个“确认”窗口,然后再在代码中做其他事情……我是通过javascript通过这种方式完成的:

out.println("<script type='text/javascript'>");
out.println("result = confirm(Do you wanna to record in DB?)");
out.println("if(result)");
out.println("  alert('will record');");
out.println("else");
out.println("  alert('will not record')");
out.println("</script>");
out.flush();

But the lines that come after of that code, are executed before that my dialog message is displayed. 但是在显示我的对话框消息之前,执行了该代码之后的代码行。 So, now I want to call different functions (where I have alert). 所以,现在我想调用不同的功能(有警报的地方)。 Functions inside my Java class/servlet... 我的Java类/ Servlet中的函数...
So... How can I call a Java function inside my javascript code? 那么...如何在我的JavaScript代码中调用Java函数? Or what I need to do to make my code wait until I confirm my message? 或者我需要做些什么来使我的代码等到确认消息之后?
Thank you 谢谢

First, you need to get clearly into your head where the respective code is executed ... and when. 首先,您需要清楚地知道执行各个代码的位置……以及何时执行。

  1. The JSP code is executed on the server side BEFORE the HTML and its embedded Javascript is sent to the browser. 在将HTML及其嵌入的Javascript发送到浏览器之前,在服务器端执行JSP代码。

  2. The Javascript code is executed on the browser size AFTER the browser has received the HTML and its embedded Javascript. 在浏览器收到HTML及其嵌入式Javascript之后,将以浏览器大小执行Java代码。

So what you want is for the Javascript to ask for a confirmation and THEN have the record saved to the database. 因此,您想要的是Javascript进行确认,然后将记录保存到数据库中。 So obviously, the record should not be saved by that JSP ... or at least not unconditionally. 因此,显然,该记录不应该由该JSP保存...或者至少不是无条件保存。 What has to happen is that the clicking of the confirmation button has to cause the Javascript to send a request to the server to say that action is confirmed. 所发生的是,单击确认按钮必须使Javascript向服务器发送一个请求,要求说操作已确认。 The sequence is: 顺序为:

  1. Client side: Requests page 客户端:请求页面
  2. Server side: Does stuff ... 服务器端:做东西...
  3. Server side: JSP formats HTML + Javascript 服务器端:JSP格式HTML + Javascript
  4. Client side: Page loads 客户端:页面加载
  5. Client side: Javascript displays confirmation dialog 客户端:Javascript显示确认对话框
  6. Client side: User says "yes" 客户端:用户说“是”
  7. Client side: Javascript causes a new request to be sent to the server side to tell it that the client has confirmed. 客户端:JavaScript导致将请求发送到服务器端,以告知客户端已确认。
  8. Server side: Performs the confirmed action. 服务器端:执行已确认的操作。
  9. Server side: Send response reporting the action. 服务器端:发送响应以报告操作。

There are a couple of ways of structure the confirmation interactions: 有两种方法来构造确认交互:

  • Step #5 could be an AJAX request in which makes a POST request using XMLHttpRequest or similar. 步骤#5可以是AJAX请求,其中使用XMLHttpRequest或类似命令发出POST请求。
  • Step #5 could be a page reload with an additional parameter to tell the server side that the save is confirmed. 步骤#5可能是页面重新加载,并带有附加参数以告知服务器端已确认保存。

In the latter case, the request could be handled by the same handler as the original request, or by a different one. 在后一种情况下,该请求可以由与原始请求相同的处理程序处理,也可以由不同的处理程序处理。

Usually, javascript runs on browser and Java class runs in your servlet container. 通常,javascript在浏览器上运行,而Java类在servlet容器中运行。 You can implement your logic by javascript and data operation by java. 您可以通过javascript实现逻辑,并通过java进行数据操作。 Jquery will help you to use ajax easily. jQuery将帮助您轻松使用ajax。

out.println("<script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-1.10.0.min.js\"></script>");
out.println("<script type='text/javascript'>");
out.println("result = confirm(Do you wanna to record in DB?)");
out.println("if(result) {");
out.println("  alert('will record');");
out.println("$.ajax({" + 
   "type: \"POST\"," + 
  "url: \"/your_servlet_url\"," + 
  "data: \"action=record\"," + 
  "success: function(msg) {" + 
  "  alert( \"Data Saved: \" + msg );" + 
  "}" + 
"});");
out.println("} else {");
out.println("  alert('will not record');");
out.println("$.ajax({" + 
   "type: \"POST\"," + 
  "url: \"/your_servlet_url\"," + 
  "data: \"action=norecord\"," + 
  "success: function(msg) {" + 
  "  alert( \"Data Saved: \" + msg );" + 
  "}" + 
"});");
out.println("}");
out.println("</script>");
out.flush();

Then you need to get what the parameter action value is and do what you want in your servlet. 然后,您需要获取参数action值是什么,并在servlet中执行所需的操作。

Unfortunately, the answer to your question is basically "you can't do that", at least not the way you are envisioning. 不幸的是,对您的问题的回答基本上是“您无法做到”,至少不是您所设想的那样。 The servlet communicates with the browser over the HTTP protocol, and the browser only understands complete web pages, one per HTTP request. Servlet通过HTTP协议与浏览器通信,浏览器仅了解完整的网页,每个HTTP请求一个。 Even if the browser did show the alert box, your server code will have no way to know if the user clicked it, because clicking an alert will not generate an HTTP request by itself. 即使浏览器确实显示了警报框,您的服务器代码也无法知道用户是否单击了它,因为单击警报将不会自行生成HTTP请求。 A new HTTP request is required whenever you want to send data back to the server, including the data representing the fact that the user clicked ok. 每当您要将数据发送回服务器(包括代表用户单击确定的事实的数据)时,都需要一个新的HTTP请求

Until the response is complete, the browser will not render the page. 在响应完成之前,浏览器将不会呈现页面。 Each request gets one response from the servlet. 每个请求都从Servlet获得一个响应。 You must complete the WHOLE response and send it all at once. 您必须完成整个答复并立即发送所有答复。 You can use if statements in the Java code while you figure out what response to send, but anything in the javascript or html will not run until the browser has recieved your completed request. 在确定要发送的响应时,可以在Java代码中使用if语句,但是在浏览器收到已完成的请求之前,javascript或html中的任何内容都不会运行。 When you called flush, you only sent the latest portion of your still incomplete page (you had not sent </body></html> and closed the connection so it's incomplete). 当您调用flush时,您仅发送了仍未完成页面的最新部分(您尚未发送</body></html>并关闭了连接,因此它不完整)。

The net result is that you cannot ask the user part way through the response what they want, or send them messages while you produce the response (ie your alert). 最终结果是,您不能在响应过程中部分询问用户他们想要什么,也不能在产生响应时(即警报)向用户发送消息。

If you want solicit user input (including button clicks) and respond to it, you must send a simple but complete page that requests the user's input, then you can do one of the following things: 如果要征求用户输入(包括按钮单击)并做出响应,则必须发送一个简单但完整的页面来请求用户输入,然后可以执行以下操作之一:

  1. Submit the user's response as a form and render a completely new page appropriate to their response. 以表单的形式提交用户的响应,并呈现一个与其响应相对应的全新页面。
  2. Submit the user's response with ajax, and respond with a page fragment that your javascript inserts into the page (AJAX). 使用ajax提交用户的响应,并使用您的JavaScript插入页面(AJAX)的页面片段进行响应。
  3. Submit the users's response with ajax, and respond with JSON data, that your javascript uses to build (or remove) elements on the page (also AJAX). 使用ajax提交用户的响应,并使用JSON数据进行响应,您的javascript使用JSON数据来构建(或删除)页面上的元素(也是AJAX)。
  4. Add enough javascript logic and data in the original page to fully respond to the user's click without sending a request to the server, possibly sending a notification to the server of the user's input after the fact. 在原始页面中添加足够的javascript逻辑和数据,以完全响应用户的单击,而无需向服务器发送请求,这可能会在事实发生后向服务器发送用户输入的通知。

The core thing to remember is that the browser and the server are separate machines and can only talk via http requests that originate from the browser . 要记住的核心是浏览器和服务器是独立的机器,并且只能通过源自浏览器的 http请求进行交谈。 The server has no way to contact the browser except in response to a request. 除了响应请求外,服务器无法联系浏览器。

Your going to need some kind of restful call. 您将需要某种轻松的通话。 If you want to implement a custom rest api look into this javascript object XMLHttpRequest() 如果您想实现自定义的rest api,请查看此javascript对象XMLHttpRequest()

or just use an html form. 或仅使用html表单。 Point it at where your httpservlet is listening. 将其指向您的httpservlet正在侦听的位置。 The downside is you only get post and get. 不利的一面是,您只能获得职位并获得职位。 eg <form action="your server" method="get/post" /> 例如<form action="your server" method="get/post" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM