
Creating an Ajax Application with Script.aculo.us
Contributed by Arun Gupta. Written and maintained by James Branam
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
Note: This document uses the NetBeans IDE 6.1 Release. If you
are using NetBeans IDE 6.5, see Creating an Ajax Application with Script.aculo.us.
Contents
To follow this tutorial, you need the following software and resources.
| NetBeans IDE |
NetBeans 6.1 Web & Java EE Version |
| Java Developer Kit (JDK) |
Version 6 or
version 5 |
JavaServer Faces Components/
Java EE Platform |
1.2 with Java EE 5* or
1.1 with J2EE 1.4
|
| GlassFish Application Server |
V2 |
| Sample Database |
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
With jMaki and JavaServer Pages, you can easily include wrapped widgets from Ajax toolkits into a JavaServer Page as a custom JSP tag. With the Netbeans jMaki plugin you can drag jMaki widgets from the Palette into a JSP. jMaki standardizes widget data and event models to simplify the programming model and to simplify interactions between widgets.
-
In the main toolbar, choose File > New Project.
The New Project wizard opens.
-
Select Java Web as the category and Web Application as the Project Type. Click Next.
Note: In NetBeans IDE 6.1, select the Web category.
-
Enter Autocomplete as the Project Name and click Next.
- Select GlassFish V2 as the Server and click Finish
-
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.
-
In the Services window, expand the Databases node, right-click the MySQL Server node, and choose Create Database.
-
Enter states as the Database Name and click OK.
-
In the New Database Connection dialog box, type the User and Password you want to use. In this tutorial, we will use duke for the User Name and duke for the Password.
Note: You must first add a user with the MySQL Admin Tool to allow access to the MySQL database.
-
In the Advanced tab of the dialog box, click OK to create the database connection.
The states database connection appears in the Services window.
-
Right-click the states database connection and choose Connect.
The icon is displayed next to the datbase connection when the database is connected.
-
Right-click the states database connection node and choose Execute Command.
The SQL Editor opens.
-
Enter the following query in the SQL Editor.
CREATE TABLE STATES ( id INT, abbrev VARCHAR(2), name VARCHAR(50), PRIMARY KEY (id) ); |
- Click Run SQL
.
- In the Services window, expand the states database connection node and the Tables folder to verify that the STATES table has been created.
- 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.
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.
-
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.
-
In the Data Souce drop down list, choose New Data Source.
The Create Data Source dialog box opens.

- Type jndi/states as the JNDI Name and select the states database connection. Click OK.
- The New Entity Classes from Database dialog box displays the fields that are available from the states database.
-
Select STATES in Available Tables and click Add.
-
Click Next. Enter server as the package name as shown in the following figure.

-
Click Create Persistence Unit.
The Create Persistence Unit dialog box opens.
- Accept the default settings and click Create to create the persistence unit.
- 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.
-
In the Projects window, expand the Configuration Files node and double-click persistence.xml.
persistence.xml opens in the IDE.
Click Add Class and in the dialog box that appears, select server.Company, and click OK. This ensures that the generated entity class is explicitly recognized by the EntityManagerFactory.

- 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: 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.
-
In the Projects window, right-click the project node and choose New > Servlet.
The New Servlet dialog box opens.
-
Type StatesServlet as the Class Name, type or select server as the Package, and click Finish.
StatesServlet.java opens in the Source Editor.
- 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();
} |
-
Replace the commented code in the processRequest method with the following code.
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>"); |
- 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.
- In the Projects window, right-click States.java to open it in the Source Editor.
-
Insert the following code directly after @NamedQueries({.
@NamedQuery(name = "States.findLikeName", query = "SELECT s FROM States s WHERE LOWER(s.name) LIKE :searchString"), |
- 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.
- Download the latest Script.aculo.us libraries from the Script.aculo.us website and unzip them.
- In the Projects window, right-click the Web Pages fiolder and choose New > Folder. Name the folder javascripts.
- 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.
- In the Projects window, double-click index.jsp to open it in the Source Editor.
-
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> |
-
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> |
-
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 in the main toolbar, or you can right-click the project node in the Projects window and choose Run.
- In the Projects window, right-click the project node and choose Run.
-
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.
- 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 download and added script.aculo.us JavaScript libraries to your project, allowing you to take advantage of Ajax functionality.
See Also
This page was last modified: October 22, 2008
|
|