Skip to main content

TOTD #39: Prototype/Script.aculo.us Autcomplete widget with MySQL, GlassFish, NetBeans

Posted by arungupta on July 29, 2008 at 9:27 AM PDT

There are several JavaScript libraries that can be embedded in your
webapplication to create a visually appealing interface. href="http://script.aculo.us/">Script.aculo.us is
one of the popular ones and is built on the href="http://www.prototypejs.org/">Prototype JavaScript
Framework. The library provides an easy-to-use, cross-browser
user interface JavaScripts that allows you to create fancy effects
commonly visible on web pages these days.



This blog entry gets you started by using href="http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter">Ajax.Autocompleter
that allows for server-powered autocompleting of text fields.
Basically, you type a character in a text field and suggestions for
possible correct values starting with that character are
shown . This is achieved by by sending an Ajax request to the
data source on server, passing the typed character in the request and
processing the response to display on the web page. This effect was
first popularized by href="http://www.google.com/webhp?complete=1&hl=en">Google
Suggest.



In this TOTD (Tip
Of style="font-weight: bold;">The style="font-weight: bold;">Day) we will create
a simple web application with a text field in a JSP page that will use
Servlet as the data source. The Servlet retrieves the parameter from
the RequestContext, uses Java Persistence API to query the database and
return response in the expected format. We will use:

Let's get started!

  1. href="http://blogs.sun.com/arungupta/entry/totd_38_creating_a_mysql">TOTD
    #38 explains how to create a MySQL Persistence Unit. Please
    follow the steps there to create a new Web application and Persistence
    Unit. Follow the steps listed below after the PU is created.
    1. In Project Explorer, expand "Source Packages", "server"
      and open "States" class. Add the following NamedQuery:


      style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
      cellpadding="2" cellspacing="2">
      @NamedQuery(name = "States.findLikeName", query =
      "SELECT s FROM States s WHERE LOWER(s.name) LIKE :searchString"),



      at the position shown below:



      src="http://blogs.sun.com/arungupta/resource/images/ps-pu-add-named-query.png">

    2. In "StatesServlet" class, replace the commented code in
      "processRequest" with the
      following fragment:


      style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
      cellpadding="2" cellspacing="2">
                 
      String searchString = request.getParameter("autocomplete_parameter");



                 
      List<States> list =
      em.createNamedQuery("States.findLikeName").

                         
      setParameter("searchString", searchString.toLowerCase() + "%").

                         
      getResultList();



                 
      out.println("<ul>");



                 
      for (int i = 0; i < list.size(); i++) {

                     
      States s = list.get(i);

                     
      out.println("<li>" + s.getName() + "</li>");

                 
      }

                 
      out.println("</ul>");



      and fix the imports by right-clicking in editor pane and selecting "Fix
      Imports".

  2. Download & Use Script.aculo.us libraries
    1. Download latest Script.aculo.us libraries from href="http://script.aculo.us/downloads">here
      (version 1.8.1 as of this writing) and unzip them.
    2. In NetBeans, right-click on "Web Pages", select "New",
      "Folder" and specify the folder name as "javascripts".
    3. From the unzipped Script.aculo.us bundle, copy all files
      from "src" and "lib" directory to the newly created "javascripts"
      folder.
    4. Expand "Web Pages" and open "index.jsp". Add the
      following fragment in HTML <head>:


      style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
      cellpadding="2" cellspacing="2">
             
      <script src="javascripts/prototype.js"
      type="text/javascript"></script>

             
      <script src="javascripts/scriptaculous.js?load=effects,controls"
      type="text/javascript"></script>

             
      <script type="text/javascript">

                 
      window.onload = function() {

                     
      new Ajax.Autocompleter("autocomplete", "autocomplete_choices",
      "/Autocomplete/StatesServlet", {});

                 
      }

             
      </script>



      and the following in HTML <body>:


      style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
      cellpadding="2" cellspacing="2">
             
      <input type="text" id="autocomplete"
      name="autocomplete_parameter"/>

             
      <div id="autocomplete_choices"
      class="autocomplete"></div>



      These fragments are part of the href="http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter">original
      tutorial.

    5. Optionally, specify a stylesheet to render the result
      nicely
      1. Create a "stylesheets" folder in "Web pages".
      2. Right -click on the newly created folder, select "New",
        "Other...", "Other" category and "Cascading Style Sheet" file type.
        Give the name "autocompleter" and click on "Finish".
      3. Replace the generated template with the following
        contents:


        style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
        cellpadding="2" cellspacing="2">
        .autocomplete {

            position:absolute;

            width:250px;

            background-color:white;

            margin:0px;

            padding:0px;

            overflow:hidden;

        }

        .autocomplete ul {

            list-style-type:none;

            margin:0px;

            padding:0px;

            overflow:auto;

        }

        .autocomplete ul li.selected { background-color: #ffb;}

        .autocomplete ul li {

            list-style-type:none;

            display:block;

            margin:0;

            padding:2px;

            height:32px;

            cursor:pointer;

        }
      4. Add the following fragment in "index.jsp" in
        <head>:


        style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
        cellpadding="2" cellspacing="2">
        <LINK
        href="stylesheets/autocompleter.css" rel="stylesheet"
        type="text/css">

Now the show time ... right-click the project and select "Run". This
deploys the project on GlassFish v2 and brings up
"http://localhost:8080/Autocomplete/index.jsp" in the default browser
window. The default page looks like:



src="http://blogs.sun.com/arungupta/resource/images/ps-output-default.png">



As you start typing characters in the text box, Ajax.Autocompleter
sends a request to the Servlet (specified using the
"/Autocomplete/StatesServlet") by passing the typed characters as query
parameters. The servlet returns an unordered HTML list. Typing "A" in
the text box shows the following output:



src="http://blogs.sun.com/arungupta/resource/images/ps-output-a.png">



and Firebug output looks like:



src="http://blogs.sun.com/arungupta/resource/images/ps-output-a-firebug.png">



Typing "C" in the text box shows the following output:



src="http://blogs.sun.com/arungupta/resource/images/ps-output-c.png">



Typing "Mi" in the text box shows the following output:



src="http://blogs.sun.com/arungupta/resource/images/ps-output-mi.png">



A request to the Servlet is made everytime a letter is typed. The
minimum number of characters that must be entered in the field before a
Servlet request is made can be altered by passing the arguments to
Ajax.Autocompleter function as shown below (changes highligted in bold):

style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
cellpadding="2" cellspacing="2">
           
window.onload = function() {

               
new Ajax.Autocompleter("autocomplete", "autocomplete_choices",
"/Autocomplete/StatesServlet", { minChars:
2
});

           
}



Some potential fun ideas to make this entry more meaningful:

  • Servlet can access data from a RESTful endpoint and
    transform the data to an unordered list
  • Autocompleter data source return data in JSON format
  • Autocompleter used in a HTML <form> and
    "afterUpdateElement" is used to process the selected entry, may be
    filter the data shown

Please leave suggestions on other TOTD (Tip Of The Day) that
you'd like to see.
A complete archive of all tips is available href="http://blogs.sun.com/arungupta/tags/totd">here.




Technorati: totd
web2.0
autocompleter
scriptaculous
prototype
javascript
glassfish
mysql href="http://technorati.com/tag/netbeans">netbeans

Related Topics >>

Comments

No offense, but this looks like a *lot* more work than it should be. Why would anyone building a "modern" web application manually build a servlet? I would *highly* recommend looking into some of the great web frameworks available today that integrate with scriptaculous. Wicket has an amazing scriptaculous extension that makes autocompletion super easy. http://wicketstuff.org/confluence/display/STUFFWIKI/Script.aculo.us+Auto...