Call Servlet and Invoke Java Code from JavaScript Along with Parameters

Call Servlet and invoke Java code from JavaScript along with parameters

Several ways:

  1. Use window.location to fire a GET request. Caveat is that it"s synchronous (so the client will see the current page being changed).

    window.location = "http://example.com/servlet?key=" + encodeURIComponent(key);

    Note the importance of built-in encodeURIComponent() function to encode the request parameters before passing it.

  2. Use form.submit() to fire a GET or POST request. The caveat is also that it"s synchronous.

    document.formname.key.value = key;
    document.formname.submit();

    With

    <form name="formname" action="servlet" method="post">
    <input type="hidden" name="key">
    </form>

    Alternatively you can also only set the hidden field of an existing form and just wait until the user submits it.

  3. Use XMLHttpRequest#send() to fire an asynchronous request in the background (also known as Ajax). Below example will invoke servlet"s doGet().

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://example.com/servlet?key=" + encodeURIComponent(key));
    xhr.send(null);

    Below example will invoke servlet"s doPost().

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://example.com/servlet");
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("key=" + encodeURIComponent(key));
  4. Use jQuery to send a crossbrowser compatible Ajax request (above xhr code works in real browsers only, for MSIE compatibility, you"ll need to add some clutter ;) ).

    $.get("http://example.com/servlet", { "key": key });

    $.post("http://example.com/servlet", { "key": key });

    Note that jQuery already transparently encodes the request parameters all by itself, so you don"t need encodeURIComponent() here.

Either way, the key will be just available by request.getParameter("key") in the servlet.

See also:

  • How to use Servlets and Ajax?
  • Access Java / Servlet / JSP / JSTL / EL variables in JavaScript

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.

Passing variable from JavaScript to servlet

You could give your hidden field an id:

.html file

Your form

<form action="">
<input type="hidden" name="myField" id="myField" value="" />
</form>

and then when you want to assign its value:

Your Javascipt

document.getElementById('myField').value = myDivText;

send the form with an action..

And at the action page your retrieve it using request.getParameter("myField")

Hope it helps

UPDATE

Hope this links help
Multipart/form-data how to get parameter hidden

How to upload files to server using JSP/Servlet?

how to send a string to a servlet from javascript using xmlhttprequest

Client Code :

 var toServer = myJSONObject.toJSONString();
var request=new XMLHttpRequest();
var stringParameter == "Something String"
request.open("POST", "http://localhost:7001/APToolbar/Main_servlet?stringParameter="+stringParameter , true);
request.send(toServer);

following string will

http://localhost:7001/APToolbar/Main_servlet?stringParameter="+stringParameter

append your parameter in url

and at server side

Server code :

String output = request.getParameter("stringParameter");
System.out.println(output);

access parameter by using stringParameter name

how to call jsp and servlet with parameter from javascript

Can call your jsp and servlet using

location.href

Here are the button link how to call jsp, and servlet.

<td><input type="button" name="edit" value="Edit" onclick="location.href='edit.jsp?id=<%=rs.getString(1)%>'; "></td>

<td><input type="button" name="delete" value="Delete" onclick="location.href='/Registrationform/DeleteServlet?id=<%=rs.getString(1)%>'; "></td>

No need to function call
It works fine..

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?

Call a Javascript function from a JSP Servlet forward

You can call that method in onload parameter of body of JSP page.

As you are already calling a JSP page using Forward method, your JSP page is getting loaded when you call it. You can call your method in body tag of JSP page as follows:

<body onload="YourMehodName()">

alternatively, you can put this script at the bottom of your JSP which will get called on loading of your page.



Related Topics



Leave a reply



Submit