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

There are several JavaScript libraries that can be embedded in your webapplication to create a visually appealing interface. Script.aculo.us is one of the popular ones and is built on the 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 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 Google Suggest.

In this TOTD (Tip Of The 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. 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:

      @NamedQuery(name = "States.findLikeName", query = "SELECT s FROM States s WHERE LOWER(s.name) LIKE :searchString"),

      at the position shown below:

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

                  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 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>:

              <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>:

              <input type="text" id="autocomplete" name="autocomplete_parameter"/>
              <div id="autocomplete_choices" class="autocomplete"></div>

      These fragments are part of the 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:

        .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>:

        <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:



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:



and Firebug output looks like:



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



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



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):
            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 here.

Technorati: totd web2.0 autocompleter scriptaculous prototype javascript glassfish mysql netbeans
Comments:

TOTD Request: For WS-Security using PKI certificates, WSIT prefers openssl-generated keys because they provide a SubjectKeyIdentifier not available with Java-keytool generated ones. I have been able to get WS-Security/PKI working well with the default client and service keys in the Glassfish keystore.jks file (located in glassfish_home/domains/domain1/config) but have no clue how to use openssl to generate my own self-signed keys with that same structure (up until now, I've only been using keytool for that). It would be great if you could show us how to use openssl to manufacture self-signed certs with the same structure as those in that keystore.jks file, and also, how to import them into a jks file afterwards (do we use openssl for keytool for that?). See here: http://tinyurl.com/6576dl .

Thanks, Glen

(BTW, if you don't want to do this, please lock Kumar of the XWSS team into a room and don't let him out until \*he\* does this. Thanks!)

Posted by Glen on August 01, 2008 at 08:53 AM PDT #

Glen, The request has been forwarded to Kumar. You may also consider posting your request to openssl-users@openssl.org.

Posted by Arun Gupta on August 03, 2008 at 11:50 PM PDT #

1. You can use Metro WS-Security with V3 certs generated by keytool.

The SubjectKeyIdentifier is not required. We have actually also updated NetBeans (in 6.5) to not require the SubjectKeyIdentifier. It is one of the many ways that can be enabled Via Policy Assertions under the X509Token Assertion.

If you need more details let me know.

2. Generating self signed certs using openssl :
I am not an openssl expert but googling gives a lot of pointers :
http://www.technocage.com/~caskey/openssl/

3. To import the cert and key pair into java keystore you will have convert to DER first :

To import these signed certificates into the keystores we will have to convert them into the binary (DER) format using 'openssl x509' command.

openssl x509 -outform DER -in selfsignedcert.pem -out selfsignedcert.cert

keytool -import -file selfsignedcert.cert -keystore keystore.jks -storepass changeit -alias myselfsignedcert

Thanks

Posted by kumar jayanti on August 04, 2008 at 03:38 AM PDT #

Thanks Kumar. (Sorry I forgot to mention to Arun for him to leave pizza in the room that he locked you in, but hopefully he thought of that anyway. :-)

Posted by Glen on August 04, 2008 at 07:45 AM PDT #

[Trackback] TOTD #39 explained how to create an Autocomplete widget (server-powered autocompleting of text fields, similar to Google Suggest) using&nbsp;Prototype/Script.aculo.us libraries with NetBeans, GlassFish and MySQL. This Tip Of The Day (TOTD) builds upon ...

Posted by Arun Gupta's Blog on August 06, 2008 at 08:08 AM PDT #

Sup

Posted by Sup on October 06, 2008 at 01:51 PM PDT #

Hi,
Can you tell me the JSON data format for the above example I tried various combination of JSON array but of no use,
Thanks,vj

Posted by vijay on September 08, 2010 at 06:41 AM PDT #

Thanks for this post.

I would like to display more than one column and only one want one item to be returned.
E.g. Ideally I would like to display employee number and name. When user selects from the drop down, I want only employee number to be returned to text box.

How can I do this?

Posted by Ponic on September 21, 2010 at 01:44 AM PDT #

Post a Comment:
Comments are closed for this entry.
About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today