简体   繁体   English

从 javascript 调用 java servlet

[英]calling a java servlet from javascript

I am trying to create a web application using the MVC design pattern.我正在尝试使用 MVC 设计模式创建一个 Web 应用程序。 For the GUI part I would like to use JavaScript.对于 GUI 部分,我想使用 JavaScript。 And for the controller Java Servlets.而对于控制器 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?有人可以帮我吗?

So you want to fire Ajax calls to the servlet?那么您想对 servlet 发出Ajax调用吗? For that you need theXMLHttpRequest object in JavaScript.为此,您需要 JavaScript 中的XMLHttpRequest对象。 Here's a Firefox compatible example:这是一个与 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 .对于触发ajaxical请求和遍历HTML DOM树的最佳跨浏览器兼容方式,我建议使用jQuery Here's a rewrite of the above in 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-pattern of /myservlet (you can change this to your taste) and have at least doGet() implemented and write the data to the response as follows:无论哪种方式,服务器上的 Servlet 都应该映射到/myservleturl-pattern (您可以根据自己的喜好更改),并且至少实现了doGet()并将数据写入响应,如下所示:

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

This should show Hello World!这应该显示Hello World! in the JavaScript alert.在 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() ,但是您应该在xhr.open()使用'POST'或在 jQuery 中使用$.post()而不是$.get()

Then, to show the data in the HTML page, you need to manipulate the HTML DOM .然后,要在 HTML 页面中显示数据,您需要操作HTML DOM For example, you have a例如,您有一个

<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.常见的格式是 XML 和 JSON。 For more elaborate examples on them, head to How to use Servlets and Ajax?有关它们的更详细示例,请前往如何使用 Servlets 和 Ajax?

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 倍。

I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for 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 调用和数据序列化的所有底层逻辑,这是一个很大的帮助。

Sorry, I read jsp not javascript.对不起,我读的是jsp而不是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):您需要执行类似操作(请注意,这是一个相对 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>
   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>
var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
  window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});

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

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