Tuesday, August 14, 2012

AJAX JQuery Tutorial

Step 1: Configure your dynamic web project,start with web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>CMIS_NEW</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>LanguageServlet</servlet-name>
<servlet-class>com.cims.LanguageServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LanguageServlet</servlet-name>
<url-pattern>/LanguageServlet</url-pattern>
</servlet-mapping>


</web-app>

Step 2: create your index.jsp which have jquery script as shown

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
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 JQUERY EXAMPLE</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#getLanguage").click(function(){
$countryName = document.getElementById("countryName").value;
$.post("LanguageServlet", {countryName:$countryName}, function(languageReturned) {
alert(languageReturned);
$("#language").html(languageReturned);
});
});
});
</script>
<form method="post">
Enter Country :
<input id="countryName" name="countryName" type="text" />
<input id="getLanguage" name="getLanguage" type="button" value="Get Language" />
</form>
<div id="language" class="outputTextArea"></div>
</body>

Step 3: Create your LanguageServlet which got hit when you post the request.

package com.cims;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LanguageServlet extends HttpServlet {

public void doPost(HttpServletRequest req,HttpServletResponse res) 
throws ServletException,IOException{

PrintWriter out = res.getWriter();
res.setContentType("text/html");
String countryName = req.getParameter("countryName");
String languageReturned = "";
if(countryName.equals("india")){
languageReturned = "Hindi";
}else if(countryName.equalsIgnoreCase("USA")){
languageReturned = "English";
}else if(countryName.equalsIgnoreCase("france")){
languageReturned = "French"; 
}else
languageReturned = "Unknown";
out.println(languageReturned);
out.flush();
out.close();



}

}


Step 4: Look at response on your JSP.



Post a Comment