Welcome!

Java Authors: Carmen Gonzalez, Lori MacVittie, Trevor Parsons, Peter Silva, Elizabeth White

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
All major researchers estimate there will be tens of billions devices – computers, smartphones, tablets, and sensors – connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo in Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be!
Noted IoT expert and researcher Joseph di Paolantonio (pictured below) has joined the @ThingsExpo faculty. Joseph, who describes himself as an “Independent Thinker” from DataArchon, will speak on the topic of “Smart Grids & Managing Big Utilities.” Over his career, Joseph di Paolantonio has worked in the energy, renewables, aerospace, telecommunications, and information technology industries. His expertise is in data analysis, system engineering, Bayesian statistics, data warehouses, business intelligence, data mining, predictive methods, and very large databases (VLDB). Prior to DataArchon, he served as a VP and Principal Analyst with Constellation Group. He is a member of the Boulder (Colo.) Brain Trust, an organization with a mission “to benefit the Business Intelligence and data management industry by providing pro bono exchange of information between vendors and independent analysts on new trends and technologies and to provide vendors with constructive feedback on their of...
Software AG helps organizations transform into Digital Enterprises, so they can differentiate from competitors and better engage customers, partners and employees. Using the Software AG Suite, companies can close the gap between business and IT to create digital systems of differentiation that drive front-line agility. We offer four on-ramps to the Digital Enterprise: alignment through collaborative process analysis; transformation through portfolio management; agility through process automation and integration; and visibility through intelligent business operations and big data.
There will be 50 billion Internet connected devices by 2020. Today, every manufacturer has a propriety protocol and an app. How do we securely integrate these "things" into our lives and businesses in a way that we can easily control and manage? Even better, how do we integrate these "things" so that they control and manage each other so our lives become more convenient or our businesses become more profitable and/or safe? We have heard that the best interface is no interface. In his session at Internet of @ThingsExpo, Chris Matthieu, Co-Founder & CTO at Octoblu, Inc., will discuss how these devices generate enough data to learn our behaviors and simplify/improve our lives. What if we could connect everything to everything? I'm not only talking about connecting things to things but also systems, cloud services, and people. Add in a little machine learning and artificial intelligence and now we have something interesting...
Last week, while in San Francisco, I used the Uber app and service four times. All four experiences were great, although one of the drivers stopped for 30 seconds and then left as I was walking up to the car. He must have realized I was a blogger. None the less, the next car was just a minute away and I suffered no pain. In this article, my colleague, Ved Sen, Global Head, Advisory Services Social, Mobile and Sensors at Cognizant shares his experiences and insights.
We are reaching the end of the beginning with WebRTC and real systems using this technology have begun to appear. One challenge that faces every WebRTC deployment (in some form or another) is identity management. For example, if you have an existing service – possibly built on a variety of different PaaS/SaaS offerings – and you want to add real-time communications you are faced with a challenge relating to user management, authentication, authorization, and validation. Service providers will want to use their existing identities, but these will have credentials already that are (hopefully) irreversibly encoded. In his session at Internet of @ThingsExpo, Peter Dunkley, Technical Director at Acision, will look at how this identity problem can be solved and discuss ways to use existing web identities for real-time communication.
Can call centers hang up the phones for good? Intuitive Solutions did. WebRTC enabled this contact center provider to eliminate antiquated telephony and desktop phone infrastructure with a pure web-based solution, allowing them to expand beyond brick-and-mortar confines to a home-based agent model. It also ensured scalability and better service for customers, including MUY! Companies, one of the country's largest franchise restaurant companies with 232 Pizza Hut locations. This is one example of WebRTC adoption today, but the potential is limitless when powered by IoT. Attendees will learn real-world benefits of WebRTC and explore future possibilities, as WebRTC and IoT intersect to improve customer service.
From telemedicine to smart cars, digital homes and industrial monitoring, the explosive growth of IoT has created exciting new business opportunities for real time calls and messaging. In his session at Internet of @ThingsExpo, Ivelin Ivanov, CEO and Co-Founder of Telestax, will share some of the new revenue sources that IoT created for Restcomm – the open source telephony platform from Telestax. Ivelin Ivanov is a technology entrepreneur who founded Mobicents, an Open Source VoIP Platform, to help create, deploy, and manage applications integrating voice, video and data. He is the co-founder of TeleStax, an Open Source Cloud Communications company that helps the shift from legacy IN/SS7 telco networks to IP-based cloud comms. An early investor in multiple start-ups, he still finds time to code for his companies and contribute to open source projects.
The Internet of Things (IoT) promises to create new business models as significant as those that were inspired by the Internet and the smartphone 20 and 10 years ago. What business, social and practical implications will this phenomenon bring? That's the subject of "Monetizing the Internet of Things: Perspectives from the Front Lines," an e-book released today and available free of charge from Aria Systems, the leading innovator in recurring revenue management.
The Internet of Things will put IT to its ultimate test by creating infinite new opportunities to digitize products and services, generate and analyze new data to improve customer satisfaction, and discover new ways to gain a competitive advantage across nearly every industry. In order to help corporate business units to capitalize on the rapidly evolving IoT opportunities, IT must stand up to a new set of challenges.
There’s Big Data, then there’s really Big Data from the Internet of Things. IoT is evolving to include many data possibilities like new types of event, log and network data. The volumes are enormous, generating tens of billions of logs per day, which raise data challenges. Early IoT deployments are relying heavily on both the cloud and managed service providers to navigate these challenges. In her session at 6th Big Data Expo®, Hannah Smalltree, Director at Treasure Data, to discuss how IoT, Big Data and deployments are processing massive data volumes from wearables, utilities and other machines.
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, Erik Lagerway, Co-founder of Hookflash, will walk through the shifting landscape of traditional telephone and voice services to the modern P2P RTC era of OTT cloud assisted services.
While great strides have been made relative to the video aspects of remote collaboration, audio technology has basically stagnated. Typically all audio is mixed to a single monaural stream and emanates from a single point, such as a speakerphone or a speaker associated with a video monitor. This leads to confusion and lack of understanding among participants especially regarding who is actually speaking. Spatial teleconferencing introduces the concept of acoustic spatial separation between conference participants in three dimensional space. This has been shown to significantly improve comprehension and conference efficiency.
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, will discuss single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example to explain some of these concepts including when to use different storage models.
SYS-CON Events announced today that Gridstore™, the leader in software-defined storage (SDS) purpose-built for Windows Servers and Hyper-V, 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. Gridstore™ is the leader in software-defined storage purpose built for virtualization that is designed to accelerate applications in virtualized environments. Using its patented Server-Side Virtual Controller™ Technology (SVCT) to eliminate the I/O blender effect and accelerate applications Gridstore delivers vmOptimized™ Storage that self-optimizes to each application or VM across both virtual and physical environments. Leveraging a grid architecture, Gridstore delivers the first end-to-end storage QoS to ensure the most important App or VM performance is never compromised. The storage grid, that uses Gridstore’s performance optimized nodes or capacity optimized nodes, starts with as few a...
The Transparent Cloud-computing Consortium (abbreviation: T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data processing High speed and high quality networks, and dramatic improvements in computer processing capabilities, have greatly changed the nature of applications and made the storing and processing of data on the network commonplace. These technological reforms have not only changed computers and smartphones, but are also changing the data processing model for all information devices. In particular, in the area known as M2M (Machine-To-Machine), there are great expectations that information with a new type of value can be produced using a variety of devices and sensors saving/sharing data via the network and through large-scale cloud-type data processing. This consortium believes that attaching a huge number of devic...
Innodisk is a service-driven provider of industrial embedded flash and DRAM storage products and technologies, with a focus on the enterprise, industrial, aerospace, and defense industries. Innodisk is dedicated to serving their customers and business partners. Quality is vitally important when it comes to industrial embedded flash and DRAM storage products. That’s why Innodisk manufactures all of their products in their own purpose-built memory production facility. In fact, they designed and built their production center to maximize manufacturing efficiency and guarantee the highest quality of our products.
Can call centers hang up the phones for good? Intuitive Solutions did. WebRTC enabled this contact center provider to eliminate antiquated telephony and desktop phone infrastructure with a pure web-based solution, allowing them to expand beyond brick-and-mortar confines to a home-based agent model. Download Slide Deck: ▸ Here
All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. Over the summer Gartner released its much anticipated annual Hype Cycle report and the big news is that Internet of Things has now replaced Big Data as the most hyped technology. Indeed, we're hearing more and more about this fascinating new technological paradigm. Every other IT news item seems to be about IoT and its implications on the future of digital business.
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.