AJAX with JSP and Servlet using Jquery Example

前端之家收集整理的这篇文章主要介绍了AJAX with JSP and Servlet using Jquery Example前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

http://www.programming-free.com/2012/08/ajax-with-jsp-and-servlet-using-jquery.html



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. You can read more about AJAX technologyhere.

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/jquery-latest.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,211)">// 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>
<url-pattern>/ActionServlet/*</url-pattern>
</servlet-mapping>

6. Last step is to run this project. Right Click on index.jsp and select Run on Server. Use your default web browser and avoid using internal web browser that is in-built in Eclipse. Now on the web page the user will be prompted to enter a name and on clicking the "Ajax Submit" button,the user will now see a welcome message saying "Hello (UserName)". This is all done asynchronously and you will not see a page refresh whenever the user clicks on the "Ajax Submit" button.

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/jquery-latest.js">
</script>
<script>
$(document).ready(function() {
</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.

Updates:

Check out these posts that are written on the same topic for know more about AJAX in Java Web Applications,

AJAX with Servlets using JQuery and JSON
AJAX Fetch Data from Database in JSP and Servlet with JSONArray

AJAX - Asynchronous Javascript and XML,47); text-decoration:none">here.

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,

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/jquery-latest.js ">
</script>
<script>
$(document).ready(function() {
$('#submit').click(function(event) {
var username=$('#user').val();
$.get('ActionServlet',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
}
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);


// 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>
<url-pattern>/ActionServlet/*</url-pattern>
</servlet-mapping>

6. Last step is to run this project. Right Click on index.jsp and select Run on Server. Use your default web browser and avoid using internal web browser that is in-built in Eclipse. Now on the web page the user will be prompted to enter a name and on clicking the "Ajax Submit" button,the user will now see a welcome message saying "Hello (UserName)". This is all done asynchronously and you will not see a page refresh whenever the user clicks on the "Ajax Submit" button.

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/jquery-latest.js">
</script>
<script>
$(document).ready(function() {
</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,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.

Updates:

Check out these posts that are written on the same topic for know more about AJAX in Java Web Applications,

AJAX with Servlets using JQuery and JSON
AJAX Fetch Data from Database in JSP and Servlet with JSONArray

猜你在找的Ajax相关文章