corner imagecorner image
FeaturesPluginsPlatformDocs & SupportCommunityPartners

Creating an Ajax Application with Script.aculo.us

This tutorial demonstrates the usage of the Java Persistence APIs to implement server side pagination (recommended for large sets of data) and to get and display the results in a text field featuring Ajax functionality. Ajax is a technology that combines (X)HTML, JavaScript, and CSS with the power of XmlHttpRequest in the creation of RIAs (Rich Internet Applications). Script.aculo.us is a set of JavaScript libraries to enhance the user interface of web sites. It provides an visual effects engine, a drag and drop library (including sortable lists), a couple of controls (Ajax-based autocompletion, in-place editing, sliders) and more.

Expected duration: 30 minutes

Contents

Content on this page applies to NetBeans IDE 6.5 and 6.7

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required
NetBeans IDE 6.5 or 6.7 Java Version
Java Developer Kit (JDK) Version 6 or version 5
GlassFish Application Server V2
Sample Database None required

* To take advantage of NetBeans IDE's Java EE 5 capabilities, use an application server that is fully compliant with the Java EE 5 specification, such as the GlassFish Application Server V2 UR2. If you are using a different server, consult the Release Notes and FAQs for known problems and workarounds. For detailed information about the supported servers and Java EE platform, see the Release Notes.

Creating the Project

First, you create the project using the New Project Wizard.

  1. In the main toolbar, choose File > New Project.

    The New Project wizard opens.
  2. Select Java Web as the category and Web Application as the Project Type. Click Next.

  3. Enter Autocomplete as the Project Name.

    New Project Wizard with Project name
  4. (Optional) Select the Use Dedicated Folder for Storing Libraries checkbox and specify the location for the libraries folder. See Sharing Project Libraries for more information on this option.
  5. Click Next.
  6. Select GlassFish V2 as the Server and click Finish
  7. index.jsp opens in the Source Editor.

Configuring the Database

In this section, you create a new MySQL database and populate the database with SQL that is provided.

  1. In the Services window, expand the Databases node, right-click the MySQL Server node, and choose Create Database.

  2. Enter states as the Database Name and click OK.

    Creat MySQl Database Dialog Box

    The states database connection appears in the Services window.

    Services window showing new database connection

    The Connected Database Icon icon is displayed next to the datbase connection when the database is connected.

  3. Right-click the states database connection node and choose Execute Command.

    The SQL Editor opens.
  4. Enter the following query in the SQL Editor.

    CREATE TABLE STATES (
    id INT,
    abbrev VARCHAR(2),
    name VARCHAR(50),
    PRIMARY KEY (id)
    );
  5. Click Run SQL RUn SQL Icon.
  6. In the Services window, expand the states database connection node and the Tables folder to verify that the states table has been created.
  7. Right-click the Tables node and choose Execute Command.
  8. In the SQL Editor, replace the existing code with the following code and click Run SQL.
    INSERT INTO STATES VALUES (1, "AL", "Alabama");
    INSERT INTO STATES VALUES (2, "AK", "Alaska");
    INSERT INTO STATES VALUES (3, "AZ", "Arizona");
    INSERT INTO STATES VALUES (4, "AR", "Arkansas");
    INSERT INTO STATES VALUES (5, "CA", "California");
    INSERT INTO STATES VALUES (6, "CO", "Colorado");
    INSERT INTO STATES VALUES (7, "CT", "Connecticut");
    INSERT INTO STATES VALUES (8, "DE", "Delaware");
    INSERT INTO STATES VALUES (9, "GL", "Florida");
    INSERT INTO STATES VALUES (10, "GA", "Georgia");
    INSERT INTO STATES VALUES (11, "HI", "Hawaii");
    INSERT INTO STATES VALUES (12, "ID", "Idaho");
    INSERT INTO STATES VALUES (13, "IL", "Illinois");
    INSERT INTO STATES VALUES (14, "IN", "Indiana");
    INSERT INTO STATES VALUES (15, "IA", "Iowa");
    INSERT INTO STATES VALUES (16, "KS", "Kansas");
    INSERT INTO STATES VALUES (17, "KY", "Kentucky");
    INSERT INTO STATES VALUES (18, "LA", "Louisiana");
    INSERT INTO STATES VALUES (19, "ME", "Maine");
    INSERT INTO STATES VALUES (20, "MD", "Maryland");
    INSERT INTO STATES VALUES (21, "MA", "Massachussetts");
    INSERT INTO STATES VALUES (22, "MI", "Michigan");
    INSERT INTO STATES VALUES (23, "MN", "Minnesota");
    INSERT INTO STATES VALUES (24, "MS", "Mississippi");
    INSERT INTO STATES VALUES (25, "MO", "Missouri");
    INSERT INTO STATES VALUES (26, "MT", "Montana");
    INSERT INTO STATES VALUES (27, "NE", "Nebraska");
    INSERT INTO STATES VALUES (28, "NV", "Nevada");
    INSERT INTO STATES VALUES (29, "NH", "New Hampshire");
    INSERT INTO STATES VALUES (30, "NJ", "New Jersey");
    INSERT INTO STATES VALUES (31, "NM", "New Mexico");
    INSERT INTO STATES VALUES (32, "NY", "New York");
    INSERT INTO STATES VALUES (33, "NC", "North Carolina");
    INSERT INTO STATES VALUES (34, "ND", "North Dakota");
    INSERT INTO STATES VALUES (35, "OH", "Ohio");
    INSERT INTO STATES VALUES (36, "OK", "Oklahoma");
    INSERT INTO STATES VALUES (37, "OR", "Orgeon");
    INSERT INTO STATES VALUES (38, "PA", "Pennsylvania");
    INSERT INTO STATES VALUES (39, "RI", "Rhode Island");
    INSERT INTO STATES VALUES (40, "SC", "South Carolina");
    INSERT INTO STATES VALUES (41, "SD", "South Dakota");
    INSERT INTO STATES VALUES (42, "TN", "Tennessee");
    INSERT INTO STATES VALUES (43, "TX", "Texas");
    INSERT INTO STATES VALUES (44, "UT", "Utah");
    INSERT INTO STATES VALUES (45, "VT", "Vermont");
    INSERT INTO STATES VALUES (46, "VA", "Virginia");
    INSERT INTO STATES VALUES (47, "WA", "Washington");
    INSERT INTO STATES VALUES (48, "WV", "West Virignia");
    INSERT INTO STATES VALUES (49, "WI", "Wisconsin");
    INSERT INTO STATES VALUES (50, "WY", "Wyoming");

    Now the database structures are created and populated. In the Services window, the states table is displayed as in the following figure.

  9. The States Database
  10. Close the SQL Editor.

Create the JPA (Java Persistence API) Entity Class

Using Java Persistence in your project greatly simplifies application development by removing the need for configuring deployment descriptors to provide object-relational mapping information for persistent fields or properties. Instead, you can use annotations to define these properties directly in a simple Java class.

Entity persistence is managed by the EntityManager API. The EntityManager API handles the persistence context, and each persistence context is a group of entity instances. When developing your application, you can use annotations in your class to specify the persistent context instance of your entity instances. The life-cycle of the entity instances is then handled by the container.

  1. In the Projects window, right-click the Autocomplete project node and choose New > Entity Classes From Database.

    The New Entity Classes from Database dialog box opens.
  2. In the Data Souce drop down list, choose New Data Source.

    The Create Data Source dialog box opens.

    Create Data Source dialog box
  3. Type jndi/states as the JNDI Name and select the states database connection. Click OK.
  4. The New Entity Classes from Database dialog box displays the fields that are available from the states database.
  5. Select STATES in Available Tables and click Add.

    New Entity Classes from Database dialog box
  6. Click Next. Enter server as the package name as shown in the following figure.

    Creating the Server Package
  7. Click Create Persistence Unit.

    The Create Persistence Unit dialog box opens.
  8. Accept the default settings and click Create to create the persistence unit.
  9. Click Finish to close the New Entity Classes from Database dialog box.

Configuring the Persistence Unit

In this section you create a persistence unit to tell the container which entity classes are to be managed by the entity manager, and also the datasource used by those entities.

You create the persistence unit by defining its properties in persistence.xml which you will create in the web module. After specifying the name of the persistence unit, you will specify the persistence provider that the container uses for managing entity instances. You also need to specify the data source and a table generation strategy. You will create the persistence unit using the New Persistence Unit wizard.

  1. In the Projects window, expand the Configuration Files node and double-click persistence.xml.

    persistence.xml opens in the IDE.
  2. Deselect the Include All Entity Classes in "Autocomplete" Module checkbox.

  3. Click Add Class and in the dialog box that appears, select server.States, and click OK. This ensures that the generated entity class is explicitly recognized by the EntityManagerFactory.

    Editing the persistence.xml file
  4. At the top of the Source Editor, select the XML view and replace <properties/> with the following code sample.

    <properties>
    <property name="toplink.jdbc.user" value="duke"/>
    <property name="toplink.jdbc.password" value="duke"/>
    </properties>

    Note: "Duke" is used as an example for the user and password. The username and password values must match the ones specified during database creation.

Creating the Servlet

In this section, you create a servlet to generate dynamic content and allow interaction with web clients (typically a browser application such as Firefox or Internet Explorer) using a request-response paradigm.

  1. In the Projects window, right-click the project node and choose New > Servlet.

    The New Servlet dialog box opens.
  2. Type StatesServlet as the Class Name, type or select server as the Package, and click Finish.

    StatesServlet.java opens in the Source Editor.
  3. Add the following code to the beginning of the StatesServlet class, right below the class declaration.
    EntityManager em;

    @Override
    public void init() throws ServletException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("AutocompletePU");
    em = emf.createEntityManager();
    }
  4. Right-click anywhere in the Source and choose Fix Imports.

  5. Find the processRequest method an insert the following code in bold.

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try { 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>"); } finally {
    out.close();
    } }
  6. Right-click anywhere in the Editor and choose Fix Imports. Make sure that java.util.List is displayed in the Fix All Imports dialog box and click OK.
  7. In the Projects window, right-click States.java to open it in the Source Editor.
  8. Insert the following bold code directly after @NamedQueries({, as seen below.

    Note: The code may appear on a single line.

    @NamedQueries({@NamedQuery(name = "States.findLikeName", query = "SELECT s FROM States s WHERE LOWER(s.name) LIKE :searchString"),
    @NamedQuery(name = "States.findAll", query = "SELECT s FROM States s"), @NamedQuery(name = "States.findById", query = "SELECT s FROM States s WHERE s.id = :id"), 
    @NamedQuery(name = "States.findByAbbrev", query = "SELECT s FROM States s WHERE s.abbrev = :abbrev"), 
    @NamedQuery(name = "States.findByName", query = "SELECT s FROM States s WHERE s.name = :name")})  
  9. Save and close StatesServlet.java and States.java.

Downloading Script.aculo.us Libraries

Script.aculo.us is a set of JavaScript libraries to enhance the user interface of web sites. It provides an visual effects engine, a drag and drop library (including sortable lists), a couple of controls (Ajax-based autocompletion, in-place editing, sliders) and more.

  1. Download the latest Script.aculo.us libraries from the Script.aculo.us website and unzip them.
  2. In the Projects window, right-click the Web Pages fiolder and choose New > Folder. Name the folder javascripts.
  3. In the unzipped Scipt.aculo.us folder, copy the contents of the src and lib directories to the javascripts folder you created in your project.
  4. In the Projects window, double-click index.jsp to open it in the Source Editor.
  5. Insert the following code between the <head> tags of index.jsp.

    <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>
  6. Insert the following code between the <body> tags, diectly below <h2>Hello World!<h2>.

    <input type="text" id="autocomplete" name="autocomplete_parameter"/>
    <div id="autocomplete_choices" class="autocomplete"></div>
  7. Optionally, insert the following CSS elements between the <head> tags to improve the look of the application.

    <style>
    div.autocomplete {
    position:absolute;
    width:250px;
    background-color:white;
    margin:0px;
    padding:0px;
    overflow:hidden;
    }
    div.autocomplete ul {
    list-style-type:none;
    margin:0px;
    padding:0px;
    overflow:auto;
    }
    div.autocomplete ul li.selected { background-color: #ffb;}
    div.autocomplete ul li {
    list-style-type:none;
    display:block;
    margin:0;
    padding:2px;
    height:32px;
    cursor:pointer;
    }
    </style>

Running the Application

Now it is time to run your project. In NetBeans IDE, there are several ways to run your project. You can click the run icon Run icon in the main toolbar, or you can right-click the project node in the Projects window and choose Run.

Note: By default, the project has been created with the Compile on Save feature enabled, so you do not need to compile your code first in order to run the application in the IDE. For more information on the Compile on Save feature, see the Compile on Save section of the Creating, Importing, and Configuring Java Projects guide.

Deployed Application
  1. In the Projects window, right-click the project node and choose Run.
  2. Test the Ajax functionality of the text field by typing a letter in the text field.

    Note how U.S. states corresponding to your entry are returned from the states database.
  3. Select one the displayed options and note that the option is entered in the text field for you.

Summary

In this tutorial, you created a Web application, created and connected to a database, and experimented with Java Persistence APIs. You added script.aculo.us JavaScript libraries to your project, allowing you to take advantage of Ajax functionality.

See Also



This page was last modified: June 18, 2009