Roopak Neevan's Blog

AJAX with Servlets : Example

Posted by: Naveen Kapoor on: July 29, 2009

 

I am going thru Head Rush Ajax and i found it quite interesting. I am following with the exampleas as well. All the examples in this book are based on PHP’s and I have never worked with PHP so initially it was difficult for me to start with but the I started with PHP and I found it easy( One reason is all code is already existing and you just need to copy that :) ).

As I am always a  servlet/JSP person, So the next question was how to intract my JSP pages with AJAX implemented javascript to my servlets.  Answer to this question is easy “GOOGLE”. Now it comes to the right serch and right resource. I tried so many options and so many pages but the info was either a complex one or not complete. After extraction bits and pieces of  info I came up with a proper AJAX code and I want to share the same with all AJAX Aspirents.

NOTE :  I have put the screen shots for the code(except the servlet and web.xml code)  as I faced lot of difficulty with code indentation. Please find the code for the below example from below link. 

 http://roopakneevan.wordpress.com/2009/07/29/ajax-with-servlets-code/

You may need to indent the code or may need to correct the code while coping the code to editor.

Eample follows here :

Step 1 )

Fig1 

Start with the JSP Page. This page contains a drop down menu and as the option in the drop down menu change based on the value this page will fetch the dynamic contents from the server using HTTPRequest.

 Step 2 )

 Fig2

Above snippet is from the JSP, Now when the drop down value will change this will call the function OnChange with parameter as the dropdown value. Lets implement it.

 Create a javascript file and name it myJSfunc.js and define your OnChange and other supporting function in the file

Fig 2.Fig 3.Fig 4.Fig 5.Fig 6.

 Step 3) 

Now we are all set with the JSP and AJAX implemented java scripts code and we are left out with the servelet. So now its time to move on to the Servlet code.

MyFirstAJAXServ.java

public class MyFirstAJAXServ extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet{           public MyFirstAJAXServ () {                        super(); }                     protected void doGet(HttpServletRequest req, HttpServletResponse resp)                                                                     throws ServletException, IOException {            // Enable this code for AJAX : first step to AJAX            String dropDownVal = req.getParameter(“SelValue”);            System.out.println(“dropDownVal : ” + dropDownVal);

            if (dropDownVal.equalsIgnoreCase(“—”)){

                 resp.setContentType(“text/xml”);

                 resp.setHeader(“Cache-Control”, “no-cache”);

                 resp.getWriter().write(“<message>This Example is created for AJAX Aspirents</message>”);

            }else if (dropDownVal.equalsIgnoreCase(“AJAX”)){

                 resp.setContentType(“text/xml”);

                 resp.setHeader(“Cache-Control”, “no-cache”);

                 resp.getWriter().write(“<message>AJAX is the term coined in February 2005 to describe a collection of technologies”+”" +

            ” used to automatically update and manipulate the information on a web page while it is being viewed”+

            ” in a browser (ie without the user having to manually refresh the page). This allows developers to”+”" +

            ” create more sophisticated web pages and applications without having to add to the native capabilities”+

            ” of the browser. A key component is the use of XMLHttpRequest, a function originally added to browsers”+”" +

            ” by Microsoft, to exchange data in the background with one or more web servers.</message>”);

            }else if (dropDownVal.equalsIgnoreCase(“JAVA”)){

                 resp.setContentType(“text/xml”);

                 resp.setHeader(“Cache-Control”, “no-cache”);

                 resp.getWriter().write(“<message>Java is a programming language expressly designed for use in the distributed environment of the Internet.” +

                “It was designed to have the look and feel of the C++ language, but it is simpler to use than C++ and enforces an ” +

                 “object-oriented programming model. Java can be used to create complete applications that may run on a single computer” +

                 ” or be distributed among servers and clients in a network. It can also be used to build a small application module or ” +

                 “applet for use as part of a Web page. Applets make it possible for a Web page user to interact with the page.</message>”);

            }else if (dropDownVal.equalsIgnoreCase(“J2EE”)){

                 resp.setContentType(“text/xml”);

                 resp.setHeader(“Cache-Control”, “no-cache”);

                 resp.getWriter().write(“<message>J2EE (Java 2 Platform, Enterprise Edition) technology and its component-based model simplify enterprise” +

                 ” development and deployment. The J2EE platform manages the infrastructure and supports the Web services to enable ” +

                 “development of secure, robust and interoperable business applications.</message>”);

                        }                      

            }                                

 protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) 

                                                                         throws ServletException, IOException {

                        //System.out.println(“Hello world”);

            }

Copy the above servelet or create your own servlet and copy the doGet function from the above code to your servlet. ** In case you are defining your own servlet please don’t forget to change the url variable in the java script with the correct servlet mapping name..

Step 4) Now we have created the Servlet, Its time to define the servlet and the mapping in web.xml.

<servlet>

      <display-name>CoffeeAjaxTest</display-name>

      <servlet-name>CoffeeAjaxTest</servlet-name>

      <servlet-class>com.ibm.nav.ajax. MyFirstAJAXServ </servlet-class>

</servlet>

 <servlet-mapping>

      <servlet-name> MyFirstAJAXServ </servlet-name>

      <url-pattern>/ MyFirstAJAXServ </url-pattern>

</servlet-mapping>

Fig 7.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


  • Diya: Hi all, I am a single mum and unfortunately cannot contact baby's father. I went to london high commission with all documents mentioned on the hci lon
  • Maty: Hi, I am planning to apply for the passport of my new born baby. But currently I am in Germany and my wife and baby is in India. My wife will apply
  • mvp: Hi, I have applied for my 3 month old baby at Pune RPO last week. Like other's mentioned the experience is very smooth. I didn't take my baby with
Follow

Get every new post delivered to your Inbox.