- AJAX Example using Servlet and JAVA
- Table of Contents
- Creating AJAX example with servlet application
- Create a servlet class
- Invoke the servlet using Ajax from html page
- Ajax Example with Servlet
- Brief Explanation:
- Conclusion
- Введение в Ajax для веб-приложений Java
- jQuery AJAX JSP Servlet Java Example
- Ajax JSP Servlet Example
- Ajax Servlet Code
- Ajax JSP Page
- jQuery AJAX JavaScript File
- Ajax JSP Servlet Example Summary
AJAX Example using Servlet and JAVA
Ajax(Asynchronous Javascript And XML) is a technique we can use in web development for creating a faster update to the user interface and better user experience. Ajax makes use of the XMLHttpRequest object to communicate with servers. Using ajax, the user can post data to the backend server without submitting the page or reloading the browser page. Creating an AJAX example application with a servlet is very simple.
In this post, we will learn how to use the Ajax technique to invoke backend servlet, get the response from the servlet and modify the user interface accordingly.
We will learn by creating a simple javascript ajax example.
Versions Details:
Table of Contents
Creating AJAX example with servlet application
We will use the Servlet for the backend that handles the requests made through Ajax call and sends JSON responses back to the browser.
Create a dynamic web project on Eclipse IDE. We are creating a Dynamic Web project called AjaxExample, as shown below.
Create a servlet class
In the previous step, we created the dynamic web project. Create a servlet class AjaxHandler.java under the src folder.
This Servlet class handles the Ajax call from our frontend html page. In this class, we are using hardcoded JSON object values as responses. Servlet class returns a JSON array as response upon invoking through Ajax call.
Note that to create JSON objects, we need to add a dependency jar to the classpath or lib of our dynamic web project. In this example, we are using the org.json dependency jar. Download the latest jar and add it to the classpath or put it under WEB-INF/ lib directory.
In the code below, We have implemented the HTTP GET method.
We are creating a JSON array and adding two JSON objects to the array. Finally, we are returning this JSON array to through response.
Our JSON object contains name and age attributes. Also, note that the response MIME type is set to application/json as we are returning JSON data.
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONObject; @WebServlet("/AjaxHandler") public class AjaxHandler extends HttpServlet < private static final long serialVersionUID = 1L; public AjaxHandler() < super(); >protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < JSONArray array = new JSONArray(); JSONObject user1 = new JSONObject(); user1.put("name", "TOM"); user1.put("age", "26"); JSONObject user2 = new JSONObject(); user2.put("name", "ASB"); user2.put("age", "26"); array.put(user1); array.put(user2); response.setContentType("application/json"); response.getWriter().write(array.toString()); >protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < doGet(request, response); >>
Invoke the servlet using Ajax from html page
In the previous step, we created our backend servlet. Now the final step is to create an html page and add Ajax call into it.
Create an html page index.html under the Webcontent folder of our dynamic web project. Add the following html content to the page.
We are calling backend servlet using the http GET method(using the XMLHttpRequest) and appending the content returned from servlet on the div html element with the id contentDiv.
#contentTable, th, tdAjax Example with Servlet
< br/>
Name | < th>Age
---|
Brief Explanation:
We have used httpRequest.open(), which opens HTTP connection for us. The first parameter(“GET” in our case) tells which HTTP request method we are going to use. Then we pass the URL of the server with the second parameter.
We can also pass a third optional parameter (with value: true or false), which notifies that whether our request is Asynchronous or not. The default value of this parameter is true.
Next, we have used the httpRequest.send() method, which sends our request to the server. We can also send any data by passing parameters to this method when we use a POST request. The data should be in the format, which the backend server can handle.
If we are POSTing the data, then we may have to set the request header with requests content-type as shown in the example below.
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
AJAX responds with ready state value as XMLHttpRequest.DONE (or value corresponding to 4) once the caller completely receives the response message from the server.
The list of ready state values are:
- 0 – Indicates request is not initialized.
- 1 – Server connection is established (or loading).
- 2 – request is received (or loaded).
- 3 – request is processing (or interactive).
- 4 – request is completed and response has been received (or complete ).
Once the response is ready, and the server responds successfully, we will get the HTTP response status code as 200 OK.
The httpRequest.response object response contains the response data sent from the server. Also, note that we have set the response type as json since we are sending the response in JSON format from our Servlet.
We can also retrieve responses by using:
- httpRequest.responseText – Returns response in the form of String or text.
- httpRequest.responseXML – Returns response in the form of XMLDocument.
Finally, It’s time to run the application.
We are using Apache Tomcat to run the application. Following is the page before making the AJAX call to the server.
After receiving the response to the browser.
Conclusion
In this article, we learned an example usage of the Ajax technique to invoke the backend servlet and retrieve the response from the servlet.
Введение в Ajax для веб-приложений Java
В этом документе содержится введение в Ajax и описываются некоторые из функций в IDE NetBeans, позволяющий сделать программирование более быстрым и более эффективным процессом при работе с технологиями, связанными с Ajax. На примере низкоуровневых функциональных возможностей Ajax продемонстрирована разработка простого приложения с функцией автозаполнения текстового поля. В документе использованы материалы статьи Грега Мюррея (Greg Murray) и демонстрационное приложение из руководства Использование Ajax при помощи технологии Java.
Ajax – это аббревиатура, означающая «Асинхронный JavaScript и XML» (Asynchronous JavaScript and XML). Основное назначение Ajax состоит в предоставлении веб-приложению возможности эффективной обработки взаимодействия между пользователем и веб-страницей, при этом значительно снижаются требования к обновлению или полной перезагрузке страницы при каждом взаимодействии с пользователем. Такой подход предоставляет широкие возможности при использовании браузера (аналогичные возможностям настольного приложения или веб-приложения на основе подключаемого модуля). Обработка взаимодействия Ajax осуществляется асинхронно в фоновом режиме. Благодаря этому пользователь может продолжать работу со страницей. Взаимодействие Ajax инициируется посредством кода JavaScript. После выполнения взаимодействия Ajax код JavaScript обновляет исходный текст HTML для страницы. Изменения вносятся немедленно без необходимости обновления страницы. Взаимодействия Ajax могут использоваться для выполнения таких задач, как проверка правильности формата вводимых записей на основе серверной логики (непосредственно во время их ввода пользователем), извлечение подробных данных из сервера, динамическое обновление данных на странице и передача элементов форм страницы.
Для работы с этим учебным курсом требуются программное обеспечение и ресурсы, перечисленные ниже.
jQuery AJAX JSP Servlet Java Example
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Ajax in Java JSP Servlet based web applications are very common. Recently I have written a lot about jQuery methods and how we can use them. Today we will look into one of the important jQuery functionality where we can easily execute AJAX calls and process the response in a Java Servlet JSP based web application.
Ajax JSP Servlet Example
I am using Eclipse IDE for creating the “Dynamic Web Project”, you can use any other IDE too. Our main focus will be towards jQuery and AJAX call from JSP to a servlet. Below image shows the final project structure.
Ajax Servlet Code
We have a very simple servlet that gets the userName from request, create a greetings and return it as plain text.
package com.journaldev.servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/GetUserServlet") public class GetUserServlet extends HttpServlet < private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < String userName = request.getParameter("userName").trim(); if(userName == null || "".equals(userName))< userName = "Guest"; >String greetings = "Hello " + userName; response.setContentType("text/plain"); response.getWriter().write(greetings); > >
Notice that I am using Servlet-3 annotations for configuration, if you like XML based configuration then you can do it in web.xml file. We will call this servlet asynchronously using jQuery AJAX support.
Ajax JSP Page
Below is our JSP page code, it has an input field where we can provide user name. As soon as focus is moved out of it, jQuery AJAX method will execute and call our servlet and process the response. index.jsp code:
Ajax Response:
Notice that we have two JS files included in the JSP page, first one is the jQuery JS library and another one contains our JS code for ajax call. I am including jQuery JS from the code.jquery.com URL, we can also download it and keep with our JS file. JSP code is very simple, we will populate ajaxGetUserServletResponse div content from the AJAX call response through jQuery.
jQuery AJAX JavaScript File
$(document).ready(function() < $('#userName').blur(function(event) < var name = $('#userName').val(); $.get('GetUserServlet', < userName : name >, function(responseText) < $('#ajaxGetUserServletResponse').text(responseText); >); >); >);
We can also make jQuery AJAX call using it’s ajax() method, as shown below. Above is the shorthand approach to using ajax() method.
$(document).ready(function() < $('#userName').blur(function() < $.ajax(< url : 'GetUserServlet', data : < userName : $('#userName').val() >, success : function(responseText) < $('#ajaxGetUserServletResponse').text(responseText); >>); >); >);
Below is the syntax of the jQuery ajax() method, try to relate it to the above code and you will understand what’s going on here.
Our jQuery Ajax JSP Servlet Example application is ready, just build and deploy it in your favorite servlet container. Below image shows the output produced, I am using Chrome Developer tools to confirm that our servlet is getting called.
Ajax JSP Servlet Example Summary
We learned the basics of jQuery AJAX support and how we can integrate it with Java web application, in next tutorials we will learn more features of jQuery that we can use in any web application. You can download the final project from the below link. Download jQuery AJAX Java Web Application Project
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us