Calling a Java Servlet from JavaScript

calling a java servlet from javascript

So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest object in JavaScript. Here's a Firefox compatible example:

<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:

<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:

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.

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

Then, to show the data in the HTML page, you need to manipulate the 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:

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

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

$('#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?

how to call servlet in JavaScript?

document.location.href is used

function func_search()
{
var srchdata = document.getElementById('searchitem').value;
//alert(srchdata);
if(srchdata == "")
{
alert("Enter Search Criteria...");
}
else
{
document.location.href="your servlet name here";
}
}

calling a java servlet from javascript ajax post method

Your servlet while defined in a .java file and compiled into a class that is stored in your WEB-INF folder, will need to be mapped to a URL (usually in your web.xml). It would not be easy to answer this without more information about what servlet container and framework you are using, but assuming you were just using pure Tomcat (without any framework like Spring) you might look at your web.xml file for something like this:

<servlet>
<servlet-name>com.project.Order</servlet-name>
<servlet-class>com.project.Order</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>com.project.Order</servlet-name>
<url-pattern>/order</url-pattern>
</servlet-mapping>

With this URL mapped you can then send HTTP POST request with some jQuery like this:

$.post("/order", $.param(data), function(response) {
document.getElementById("Table").innerHTML = "Considered table number " + response + " for you";
});

Calling Servlet from JavaScript

Try this code

<a href="#" onclick="callServlet()"><img
src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_buynow_pp_142x27.png"
alt="PayPal - The safer, easier way to pay online!"></a>

EDIT:

Finally we discovered that a servlet should be mapped without extension and doGet method is used to get the request from javascript.

Calling Javascript function from Servlet

response.getWriter().println("<script type='text/javascript'>jAlert('Hello');</script>");

This above code will never be rendered on the browser since you are forwarding you request to a JSP page, either using RequestDispatcher or using sendRedirect method. In both option, response will only be generated for what you have written on your JSP.

How to call servlet from javascript

This can be done using ajax

<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/testmail/dataentry", true);
xmlhttp.send();
}
</script>

Calling Servlet with jquery

Based on your statement, I would assume steps 1-3 are working and what you actually are asking for help with is step 4. In that case, what you are looking for seem to be an ajax request to the servlet, something like

$.ajax({
method: "POST",
url: "/loginServlet",
data: { username: "username", password: "password" }
})
.success(function(){
//do success stuff
})
.error(function(){
//do error handling stuff
});

If the user validation turns out a success, you can just redirect in the servlet, using something like

response.sendRedirect(targetUrl);

It may be useful for your development to read up a bit on the jQuery.ajax function. It's quite good to know.

http://api.jquery.com/jquery.ajax/

Also, if you want to cancel the submit behaviour, it may be preferable to use click instead of submit, i.e. change button type to button instead of submit and either add onclick to the button markup or through jQuery.

Calling a servlet from a JavaScript with request parameters

Some comments:

  1. Since you already include jQuery, use the ajax() function. It has much better error handling and solves many corner cases for you.

  2. Update to a more recent version of jQuery. The latest release is 1.7.2.

  3. localhost will only work if the server is on the same machine as the browser. OK during development but will break when you deploy. Either get rid of it (then the browser will prepend it for you) or make sure the URL is generated from the servlet context.



Related Topics



Leave a reply



Submit