从 javascript 调用 java servlet

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3028490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:44:54  来源:igfitidea点击:

calling a java servlet from javascript

javajavascriptajaxweb-applicationsservlets

提问by woolagaroo

I am trying to create a web application using the MVC design pattern. For the GUI part I would like to use JavaScript. And for the controller Java Servlets.

我正在尝试使用 MVC 设计模式创建一个 Web 应用程序。对于 GUI 部分,我想使用 JavaScript。而对于控制器 Java Servlets。

Now I have never really worked with JavaScript, so I'm having a hard time figuring out how to call a Java Servlet from JavaScript and how to get the response from the Servlet.

现在我从来没有真正使用过 JavaScript,所以我很难弄清楚如何从 JavaScript 调用 Java Servlet 以及如何从 Servlet 获取响应。

Can anybody help me out?

有人可以帮我吗?

采纳答案by BalusC

So you want to fire Ajaxcalls to the servlet? For that you need the XMLHttpRequestobject in JavaScript. Here's a Firefox compatible example:

那么您想对servlet 发出Ajax调用吗?为此,您需要XMLHttpRequestJavaScript 中的对象。这是一个与 Firefox 兼容的示例:

<script>
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var data = xhr.responseText;
            alert(data);
        }
    }
    xhr.open('GET', '${pageContext.request.contextPath}/myservlet', true);
    xhr.send(null);
</script>

This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:

然而,这是非常冗长的并且不是真正的跨浏览器兼容。对于触发ajaxical请求和遍历HTML DOM树的最佳跨浏览器兼容方式,我建议使用jQuery。这是在 jQuery 中对上述内容的重写:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $.get('${pageContext.request.contextPath}/myservlet', function(data) {
        alert(data);
    });
</script>

Either way, the Servlet on the server should be mapped on an url-patternof /myservlet(you can change this to your taste) and have at least doGet()implemented and write the data to the response as follows:

无论哪种方式,服务器上的 Servlet 都应该映射到url-patternof /myservlet(您可以根据自己的喜好进行更改),并且至少已doGet()实现并将数据写入响应,如下所示:

String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);

This should show Hello World!in the JavaScript alert.

这应该显示Hello World!在 JavaScript 警报中。

You can of course also use doPost(), but then you should use 'POST'in xhr.open()or use $.post()instead of $.get()in jQuery.

您可以当然也可以使用doPost(),但你应该使用'POST'xhr.open()或使用$.post(),而不是$.get()在jQuery的。

Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a

然后,要在 HTML 页面中显示数据,您需要操作HTML DOM。例如,您有一个

<div id="data"></div>

in the HTML where you'd like to display the response data, then you can do so instead of alert(data)of the 1st example:

在您想要显示响应数据的 HTML 中,您可以这样做而不是alert(data)第一个示例:

document.getElementById("data").firstChild.nodeValue = data;

In the jQuery example you could do this in a more concise and nice way:

在 jQuery 示例中,您可以以更简洁和漂亮的方式执行此操作:

$('#data').text(data);

To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. For more elaborate examples on them, head to How to use Servlets and Ajax?

为了更进一步,您需要一种易于访问的数据格式来传输更复杂的数据。常见的格式是 XML 和 JSON。有关它们的更详细示例,请前往如何使用 Servlets 和 Ajax?

回答by krock

Sorry, I read jsp not javascript. You need to do something like (note that this is a relative url and may be different depending on the url of the document this javascript is in):

对不起,我读的是jsp而不是javascript。您需要执行类似操作(请注意,这是一个相对 url,并且可能会因该 javascript 所在文档的 url 不同而有所不同):

document.location = 'path/to/servlet';

Where your servlet-mapping in web.xml looks something like this:

web.xml 中的 servlet 映射如下所示:

<servlet-mapping>
    <servlet-name>someServlet</servlet-name>
    <url-pattern>/path/to/servlet*</url-pattern>
</servlet-mapping>

回答by migsho

I really recommend you use jqueryfor the javascript calls and some implementation of JSR311 like jerseyfor the service layer, which would delegate to your controllers.

我真的建议您将jquery用于 javascript 调用和 JSR311 的一些实现,例如用于服务层的jersey,它将委托给您的控制器。

This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.

这将帮助您处理处理 HTTP 调用和数据序列化的所有底层逻辑,这是一个很大的帮助。

回答by Johan Lund

The code here will use AJAX to print text to an HTML5 document dynamically (Ajax code is similar to book Internet & WWW (Deitel)):

这里的代码将使用 AJAX 将文本动态打印到 HTML5 文档中(Ajax 代码类似于 book Internet & WWW (Deitel)):

Javascript code:

Javascript代码:

var asyncRequest;    
function start(){
    try
    {
        asyncRequest = new XMLHttpRequest();
        asyncRequest.addEventListener("readystatechange", stateChange, false);
        asyncRequest.open('GET', '/Test', true);    //   /Test is url to Servlet!
        asyncRequest.send(null);
    }
    catch(exception)
   {
    alert("Request failed");
   }
}

function stateChange(){
if(asyncRequest.readyState == 4 && asyncRequest.status == 200)
    {
    var text = document.getElementById("text");         //  text is an id of a 
    text.innerHTML = asyncRequest.responseText;         //  div in HTML document
    }
}

window.addEventListener("load", start(), false);

Servlet java code:

Servlet Java 代码:

public class Test extends HttpServlet{
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException{
        resp.setContentType("text/plain");
        resp.getWriter().println("Servlet wrote this! (Test.java)");
    }
}

HTML document

HTML 文档

 <div id = "text"></div>

EDIT

编辑

I wrote answer above when I was new with web programming. I let it stand, but the javascript part should definitely be in jQuery instead, it is 10 times easier than raw javascript.

当我刚接触网络编程时,我在上面写了答案。我让它站着,但 javascript 部分绝对应该在 jQuery 中,它比原始 javascript 容易 10 倍。

回答by Sanket Parchande

   function callServlet()


{
 document.getElementById("adminForm").action="./Administrator";
 document.getElementById("adminForm").method = "GET";
 document.getElementById("adminForm").submit();

}

}

<button type="submit"  onclick="callServlet()" align="center"> Register</button>

回答by matak8s

var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
  window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});