pTutorial

New way to learn Programming

AJAX tutorial with servlet

Ajax is a programming language independent concept so you can create dynamic pages with Ajax using any server side programming language like JSP (Java server page), java servlet, PHP etc. Here we are using Servlet for generating the server-side program.

This section covers the basic and advance example with Servlet like load another Servlet class data, Ajax database example and many more.

Following example simply print the user name without reloading the whole web page.

Ajax Example with servlet

<!--index.html-->

<html>
<head>
<script>
var request;
function table()
{
var u=document.frm.num.value;
var url="welcome?val="+u;
if(window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange=getInfo;
request.open("GET",url,true);
request.send();
}
function getInfo(){
if(request.readyState==4){
var val=request.responseText;
document.getElementById('uk').innerHTML=val;
}
}

</script>
</head>
<body>
    <h2>Please Enter your anything to check response</h2>
<form name="frm">
<input type="text" name="num" onKeyUp="table()">
</form>

<span id="uk"> </span>

</body>
</html>

Servlet Class

Simple Java Servlet class to get parameter from the index.html and print the response.

import javax.servlet.http.*;  
import javax.servlet.*;  
import java.io.*;  
public class DemoServlet extends HttpServlet{  
public void service(HttpServletRequest req,HttpServletResponse res)  
throws ServletException,IOException  
{  
res.setContentType("text/html");
PrintWriter pw=res.getWriter();  
String name=req.getParameter("val");  
pw.println("<html><body>");  
pw.println(name);  
pw.println("</body></html>");  
pw.close();  
}
}  

XML for servlet

<web-app>  
<servlet>  
<servlet-name>DemoServlet</servlet-name>  
<servlet-class>DemoServlet</servlet-class>  
</servlet>  
  
<servlet-mapping>  
<servlet-name>DemoServlet</servlet-name>  
<url-pattern>/welcome</url-pattern>  
</servlet-mapping>  
 </web-app>  
<web-app>  
  
<servlet>  
<servlet-name>DemoServlet</servlet-name>  
<servlet-class>DemoServlet</servlet-class>  
</servlet>  
  
<servlet-mapping>  
<servlet-name>DemoServlet</servlet-name>  
<url-pattern>/welcome</url-pattern>  
</servlet-mapping>  
</web-app>  

See Also


QUOTES OF THE DAY

Whenever man commits a crime,heaven finds a witness.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER