Welcome!

Java Authors: Trevor Parsons, Esmeralda Swartz, Sandi Mappic, Carmen Gonzalez, Pat Romanski

Related Topics: Java, Linux, Open Source, Eclipse

Java: Tutorial

Using Ext JS, Servlets, JSON, MySQL and Tomcat on Fedora

A simple how to

Java Developer Magazine on Ulitzer

These days the popularity of Ext JS (a JavaScript library) is gaining momentum. One of the most popular widgets within Ext JS is the DataGrid. The reason - displaying data from a database is one of the most common tasks of a web application. "Out of the box" the DataGrid has functionality (for instance, ascending or descending sorting and reordering of columns by dragging it) that otherwise would require some effort from developers. Another attractive feature of the DataGrid is that it can use JSON (JavaScript Object Notation), which allows you to reduce traffic in comparison with full Swing HTML or XML formatting on the server.

Examples from Ext JS site [1] and Ext JS books such as Learning Ext JS.Packt Publishing [2] are focused on PHP in conjunction with Ext JS.

However, what if your organization already uses servlets for web applications?

Googling the problem will lead to a number of "spotted" solutions in which key details are often missed. Besides, there is no "out of the box" JSON support in Java. Sure, you can do it manually but why reinvent the wheel?

This article will show you how to build a servlet-based web application with Ext JS from scratch, and will save you a lot of time on configuration issues that are usually hard to fix.

Example: Phone Book
The following describes how a phone book will be used within this article as it is usually easy to learn by example.

Suppose you need to create a web application to read a phone book for your organization.

As your clients and/or customers can be located all over the world, you need to have a "country" column within a database table in which the phone book is stored. Also suppose it's required to have a First Name, Last Name, Middle Name, Phone Number, Type of phone (home, office, etc.), Description (in here some useful information about a phone can be placed). Foreign names and phones (as dialed from the U.S.) can be long, so it's reasonable to store said information in lengthy enough fields.

For production, the possible length of fields should be researched carefully, but for our example let's assume it will be 250 characters. Of course, you will be able to easily change it if necessary. All names, companies and phones used in this example are entirely fictional. Any possible coincident with reality is by accident only. Data for the example will be stored in a table called phone1 of the MySQL phonebook database.

MySQL and Fedora
MySQL is a popular free open source database for Internet applications. At the time of writing the possible future of MySQL within Oracle was widely discussed (please see for example [3]). However, consider a big installation base and the fact that MySQL packages can be found for most Linux distributions, it will be safe to assume that MySQL will be used at least in the short term.

As an example of Linux, the popular Fedora distribution will be used within the article. With minimal effort, results can be reproduced in other distributions such as Ubuntu.

Configuration in which methods from this article were developed includes a virtual machine with Fedora on a Windows host. Please see my articles [4, 5] on how to use it effectively.

The installation procedure for MySQL on Fedora with yum is described in [6]. If you don't want to start MySQL each time you start Fedora, you may want to create a launcher with the following command:

service mysqld start

and place it, for instance, on your GNOME desktop.

Another useful script given below will allow you to easily start the mysql command within your terminal window

mysql -u <yourUserName> -p<yourPassword>

in the above script <yourUserName> and <yourPassword> should be substituted with your user name and password, respectively. Please note that there is a blank between -u and <yourUserName> but there is no blank between -p and <yourPassword>. You may want to place the script under some directory from your path. If you want a GUI tool for MySQL, it is recommended that you use Oracle SQL developer [7] rather than native MySQL GUI tools. The reason is the flexibility of Oracle SQL developer (for instance you can use it both with MySQL 5.x and Oracle 11g). Download the latest release of Oracle SQL developer  from [7]. At the time of writing Linux RPM of the release is sqldeveloper-1.5.4.59.40-1.noarch.rpm.

Installation can be performed by running the following command:

rpm -Uhv sqldeveloper-1.5.4.59.40-1.noarch.rpm

within the Fedora terminal window.

After that SQL Developer can be found under Applications | Programming of the GNOME menu. From here SQL Developer launchers can be added to the desktop or panel by right-clicking and making a corresponding choice.

The only additional thing that you will need to use is the JDBC driver for MySQL. At the time of writing it is recommended you select from the Oracle SQL developer menu Help | Check for updates, click Next. Than select Third-Party Extensions, click Next and select MySQL JDBC driver (assuming that your computer is connected to Internet). Please visit [7] for latest updates on Oracle SQL developer. Both mysql command, Oracle SQL developer and described below Ganymede Data Source Explorer can be used together as convenient.

Tomcat 6, MySQL and Dolphin
It is assumed within the article that Java SDK from Sun is used rather than the native Java that comes with Fedora. At the time of writing it was possible to use http://www.mjmwired.net/resources and select your Fedora release (say Fedora 10) for a "how to" on this subject. If this resource will not be available, you may want to Google for "Personal Fedora <your release number here> installation guide".

The easiest way to install Tomcat 6 on Fedora is to issue the following command within terminal window:

yum install tomcat6

The above command will install Tomcat 6 as a service. Assuming that you don't want to run Tomcat 6 each time you start Fedora, use the following commands within the terminal window. To start Tomcat 6 use:

service tomcat6 start

To stop Tomcat 6 use:

service tomcat6 stop

You may want to create launchers with these commands to conveniently start and stop Tomcat 6.

Web applications by default are located under /var/lib/tomcat6/webapps. Tomcat 6 libraries are located under /usr/share/tomcat6/lib. To work with MySQL you will need to download MySQL Connector/J tarball from the appropriate mirror mentioned here.

At the time of writing, a file with the latest connector is mysql-connector-java-5.1.7-bin.jar (tarball file name is mysql-connector-java-5.1.7.tar.gz). Check the site in question for updates.

It's convenient to use Dolphin (a file manager for KDE) to extract files from a tarball. Dolphin can be used under GNOME as well. You can start a Dolphin, navigate to the location of a tarball and double-click on the tarball. Dolphin will open the tarball just like a regular folder. Then you may locate the needed file, files or folders, select them (if the entire contents of a certain folder is needed, just select the folder or open the folder and press CTRL+A) and press CTRL + C. Then navigate to your destination and press CTRL + V to copy files selected from a tarball. That's it.

This way you can copy mysql-connector-java-5.1.7-bin.jar from the tarball to /usr/share/tomcat6/lib.

Ganymede
It's convenient to use an IDE to develop servlets. One of the most popular is Eclipse. The latest release of Eclipse at the time of writing is Ganymede, which can be downloaded from http://www.eclipse.org/downloads/. It's recommended to use at least the Eclipse IDE for Java EE Developers distribution of Ganymede. To install Ganymede just open Ganymede tarball (which is eclipse-jee-ganymede-SR2-linux-gtk.tar.gz at the time of writing) with Dolphin and copy the Eclipse folder under the desired location. A detailed description of Ganymede options is far beyond the scope of this article. However, one of them, namely the GUI, for work in particular with databases (in Ganymede terms it is Data Source Explorer) will be described.

  • To get to the Data Source Explorer select Window | Show View | Data Source Explorer from the Ganymede menu. Within Data Source Explorer navigate to Data Base Connections.
  • Once in here right-click and select New.
  • Select MySQL from a drop-down list and click Next.
  • Click the New Driver Definition button, which is a little circle with lines in it.
  • Select the MySQL JDBC driver MySQL 5.1.
  • Click the Jar List tab. Click Add Jar/Zip button.
  • Browse to /usr/share/tomcat6/lib/mysql-connector-java-5.1.7-bin.jar and select it.
  • Click Remove Jar/Zip button to remove mysql-connector-java-5.1.0-bin.jar, which is the Ganymede default.
  • Click the Properties tab to set up the correct connection URL, database name, password and user ID.

In Ganymede terms, the previously described operation is known as a connection profile creation.

  • Within the Data Source Explorer window click on the triangle that is located left of Data Base Connection folder. The name of your database will appear under your connection.
  • Click on a triangle left of the name. Authorization IDs and Schemas folders will appear.
  • Click on a triangle left of the Schemas folder. A representation of the schema of your database will appear.
  • Click on a triangle left of it. Folders named Dependencies, Stored Procedures and Tables will appear among others. Click on a triangle left of Tables. A list of tables from your database will appear. Select the needed table.
  • Right-click on it and select Data | Edit from the pop-up menu.

That's it. From this point you will be able to view and edit data directly from your table within the window named after the table in question. There is no Save button within said window so how do you save your work? Suppose you edited data, clicked on a row next to one in which data was changed, and after that attempted to close said window. In this case a Save Resource window will appear. You will be offered three options: Yes, No and Cancel. If you select Yes, said data will be saved. In this case Ganymede will generate and execute a corresponding SQL Update command for you. Ganymede will also report on results of the execution.

MySQL Stored Procedure for the Example
Usage of stored procedures rather than direct SQL statements in JDBC is highly recommended. The reasons are high execution speed, reduction of traffic (only needed parameters are transferred to a database, not a whole SQL statement) and improvements in security. The creation of stored procedures within MySQL is simple. Just set the delimiter to some symbol that you will not use in your procedure (say to "|"). In this simple example we will just select data from phone1 table. The reaction of our stored procedure within the MySQL command is shown below:

mysql> delimiter | ;
mysql> create procedure read_phonebook()
-> begin
-> select * from phone1;
-> end;
-> |

After that a delimiter can be set back to ";" and a procedure checked for accuracy by using

call read_phonebook();
statement.

Servlet with JSON-type Response
The source code of the servlet is given in Listing 1. Here are some comments for your convenience.

To bring JSON-type results to the HTML page with Ext JS one can use:

res.setContentType("text/html");

In the previous sentence res is an instance of HttpServletResponse. The result set using stored procedure described in the previous section can be obtained as follows:

CallableStatement stExtJS = connExtJS.prepareCall("{call read_phonebook()}");
stExtJS.execute();
ResultSet rsExtJS = stExtJS.getResultSet();

Please note that the datasource used in Listing 1 should be described within META-INF/context.xml

To interact with Ext JS we need to put "[" at the beginning  and "]" at the end of the information produced by the servlet.

Java (and specifically servlets) do not support JSON notation "out of the box." Rather than develop a "homemade" solution, it is recommended you use the free open source library, which is proven to be effective. For our example, json_simple-1.1.jar is chosen for its simplicity and effectiveness. The file can be obtained from this at the time of writing. Please contact me, if this resource is not available. You will need to include this file both in Build Path for your Ganymede project and in WEB-INF/lib for the servlet.

json_simple-1.1 automatically encloses the appropriate data with curly brackets; however, it is your job to put a comma (",") between said data (please see Listing 1 for more details on this).

Please note that of course json_simple-1.1 is not a "silver bullet." You need to research other libraries that implement JSON on Java to see what will fit your needs (for instance google-gson from http://code.google.com/p/google-gson/).

Putting It All Together: Ext JS, JSON, Tomcat
As a standalone, Tomcat is used both as a web server and a sevlet/JSP container, you may want to place your HTML page (or pages) for Ext JS under /var/lib/tomcat6/webapps/<YourApplicationName>. Replace <YourApplicationName> from previous sentence with the needed name of your application.

In the same directory, the corresponding war file or META-INF, WEB-INF for the servlet in question as well as extjs (a folder with Ext JS distribution that you downloaded from [1] and unzipped) and  JavaScript file(s) that will be used by the page(s) will be located.

In this case, the necessary HTML link elements for Ext JS components will be made like this one:

<link rel="stylesheet" href="extjs/resources/css/ext-all.css" />

Please note that path starts with extjs. Using the given link element as an example, you can easily write similar ones for ext-base.js and ext-all.js.

For our example, the name of the page is phone_book.html. This page uses phonebook.js JavaScript file, which in turn works with Ext JS and the servlet in question. Page and JavaScript file do not use any complicated constructions and are very much self-explanatory (please see Listing 2 and Listing 3 for details). It should be mentioned, however, that instead of the traditional PHP scripts, a reference to the URL for the servlet from the previous section (as it is described in web.xml) is used within the JavaScript file. Said reference has the following form:

url: '<nameOfTheServletAsItDescribedInWebXML>'.

Replace  < nameOfTheServletAsItDescribedInWebXML > from the previous sentence with the needed name.

What Do We Have?
Now when all the groundwork is done, what do we get in exchange?

With Ext JS a user can drag and drop columns, sort columns in the desired order and decide which columns to display as shown in Figure 1. Note that only checked columns from Figure 1 are displayed. If, for instance, we uncheck some of the columns, the result will be given in Figure 2.

Without writing any additional code that handles drag-and-drop, sorting, and partial displaying logic, we obtained the mentioned functionality by using simple methods described in this article together with Ext JS JSON, MySQL, Tomcat, and Fedora.

Resources

  1. Ext JS site
  2. Frederic S., Ramsay C. and Blades S.'C'. Learning Ext JS.Packt Publishing. 2008. ISBN-10: 1847195148.
  3. Schutzberg A. Oracle Buys Sun: What Happens to MySQL?
  4. Krivitsky A. Running Fedora Core 5 Under Windows XP - Tips and Tricks, LinuxWorld magazine, vol.4, issue 5, 2006, pp. 28 - 30
  5. Krivitsky A. The 'Best of Both Worlds': Running Fedora 8 on Legacy Windows XP.
  6. Negus C. Fedora 9 and Red Hat Enterprise Linux Bible. Wiley Publishing Inc. 2008. ISBN: 978-0-470-37362-0
  7. Oracle SQL Developer

More Stories By Anatoly Krivitsky

Anatoly Krivitsky has a PhD in computer science and has more than 24 years of working experience in the IT field. He's the author of 20 published papers and books and five patents. For more information, please visit http://www.myjavaserver.com/~akrivitsky/index.html.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that Utimaco will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
Predicted by Gartner to add $1.9 trillion to the global economy by 2020, the Internet of Everything (IoE) is based on the idea that devices, systems and services will connect in simple, transparent ways, enabling seamless interactions among devices across brands and sectors. As this vision unfolds, it is clear that no single company can accomplish the level of interoperability required to support the horizontal aspects of the IoE. The AllSeen Alliance, announced in December 2013, was formed with the goal to advance IoE adoption and innovation in the connected home, healthcare, education, aut...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...