AJAX - Asynchronous Javascript and
XML, is a technology that enables web applications to behave more like desktop
applications by making asynchronous calls to the server. This eliminates the
process of doing a complete page refresh while we need only a small part of the
page to be updated. Google's Auto Suggest is a best example for AJAX
implementation. As we type our search terms in the search box, Google gives us
suggestions according to the search terms we type without refreshing the page.
AJAX is implemented using Javascript
and XML. XMLHttpRequest is the object that does the job behind the scene. You
can also use JSON ( Javascript Object Notation) instead of XML. In this post, I
am going to demonstrate with a simple example on how to make AJAX calls from a
JSP page to a Servlet using JQuery and update the same JSP page back with the
response from the Servlet. In other words, this post will give you an overview
on how to implement AJAX calls in Java web applications. I am using JQuery
library instead of implementing this in Javascript because it is quite tedious
to make it work across all browsers in Javascript and JQuery simplifies this in
a single function. Here are the steps to reproduce to create a simple AJAX
enabled Java Web Application using Eclipse and Tomcat 7,
1. Create a Dynamic Web Project in
Eclipse. I have named it as "JQueryAjaxDemo"
2. Now right click on the Webcontent
folder in the Project Explorer and create a JSP file. I have named it as
"index.jsp".
3. In the index.jsp page, let us
have a text box where the user will be prompted to enter his/her name and a
button to display a welcome message with the name given by the user in the
textbox on clicking it. Copy paste the below code in index.jsp file.
<%@ page
language="java" contentType="text/html; charset=UTF-8"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>AJAX
calls using Jquery in Servlet</title>
<script src="http://code.jquery.com/jquerylatest.min.js">
</script>
<script src="http://code.jquery.com/jquerylatest.min.js">
</script>
<script>
$(document).ready(function() {
$('#submit').click(function(event) {
var
username=$('#user').val();
$.get('ActionServlet',{user:username},function(responseText)
{
$('#welcometext').text(responseText);
});
});
});
</script>
</head>
<body>
<form
id="form1">
<h1>AJAX
Demo using Jquery in JSP and Servlet</h1>
Enter your Name:
<input
type="text" id="user"/>
<input
type="button" id="submit" value="Ajax
Submit"/>
<br/>
<div
id="welcometext">
</div>
</form>
</body>
</html>
3. Right click on Source directory
and create a new Package. Name it as "ajaxdemo".
4. Right click on Source directory
and Add -> New -> Servlet and name it as "ActionServlet". In
this servlet we get the name entered by the user in the jsp page and create a
welcome message that includes this name. This is then returned back to the jsp
page to be displayed to the user. If no name is typed by the user in the
textbox, then it is defaulted to a value called "User". Copy and
paste the below code in 'ActionServlet.java' file.
package ajaxdemo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ActionServlet
*/
public class ActionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ActionServlet() {
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=null;
name = "Hello "+request.getParameter("user");
if(request.getParameter("user").toString().equals("")){
name="Hello User";
}
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(name);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Note: If you choose to use a different name for package and servlet, provide the same name for url mapping in the deployment descriptor explained in the next step.
5. Now map the above servlet to an url pattern so that the servlet will be called whenever it matches the specified url pattern. Open web.xml file that is under WEB-INF folder and paste the below code above </web-app> tag.
package ajaxdemo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ActionServlet
*/
public class ActionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ActionServlet() {
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=null;
name = "Hello "+request.getParameter("user");
if(request.getParameter("user").toString().equals("")){
name="Hello User";
}
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(name);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Note: If you choose to use a different name for package and servlet, provide the same name for url mapping in the deployment descriptor explained in the next step.
5. Now map the above servlet to an url pattern so that the servlet will be called whenever it matches the specified url pattern. Open web.xml file that is under WEB-INF folder and paste the below code above </web-app> tag.
<servlet>
<servlet-name>ActionServlet</servlet-name>
<servlet-class>ajaxdemo.ActionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ActionServlet</servlet-name>
<url-pattern>/ActionServlet/*</url-pattern>
</servlet-mapping>
Code
Explanation
The JQuery code written on the head section of the jsp page
is responsible for the AJAX call made to the servlet and displaying the
response back in the JSP page.
<script
src="http://code.jquery.com/jquerylatest.min.js">
</script>
</script>
<script>
$(document).ready(function() {
var
username=$('#user').val();
$.get('ActionServlet',{user:username},function(responseText)
{
$('#welcometext').text(responseText);
});
});
});
</script>
When the user clicks on "Ajax Submit" button, button click event is fired and the 'get' function executes the Ajax GET request on the Servlet(ActionServlet in the above example). The second argument of the get function is a key-value pair that passes the input value from JSP page to Servlet. The third argument is a function that defines what is to be done with the response that is got back from the servlet. For better understanding download the source code of the above example from the below link and run it yourself with small alterations in the Servlet and JSP page.
If you want to add more dynamics and
return other Java objects such as list, map, etc. as response instead of plain
text then you can use JSON. I am aiming to provide a simple example for this in
my upcoming post.
Please
leave your comments and queries about this post in the comment sections in
order for me to improve my writing skills and to showcase more useful posts.
0 comments:
Post a Comment