Welcome!

Java Authors: Liz McMillan, Sematext Blog , Elizabeth White, Charles Jolley, Torben Andersen

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
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...
"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

The BPM world is going through some evolution or changes where traditional business process management solutions really have nowhere to go in terms of development of the road map. In this demo at 15th Cloud Expo, Kyle Hansen, Director of Professional Services at AgilePoint, shows AgilePoint’s unique approach to dealing with this market circumstance by developing a rapid application composition or development framework.
“In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
DevOps Summit 2015 New York, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential.
"People are a lot more knowledgeable about APIs now. There are two types of people who work with APIs - IT people who want to use APIs for something internal and the product managers who want to do something outside APIs for people to connect to them," explained Roberto Medrano, Executive Vice President at SOA Software, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Nigeria has the largest economy in Africa, at more than US$500 billion, and ranks 23rd in the world. A recent re-evaluation of Nigeria's true economic size doubled the previous estimate, and brought it well ahead of South Africa, which is a member (unlike Nigeria) of the G20 club for political as well as economic reasons. Nigeria's economy can be said to be quite diverse from one point of view, but heavily dependent on oil and gas at the same time. Oil and natural gas account for about 15% of Nigera's overall economy, but traditionally represent more than 90% of the country's exports and as...
The Internet of Things is a misnomer. That implies that everything is on the Internet, and that simply should not be - especially for things that are blurring the line between medical devices that stimulate like a pacemaker and quantified self-sensors like a pedometer or pulse tracker. The mesh of things that we manage must be segmented into zones of trust for sensing data, transmitting data, receiving command and control administrative changes, and peer-to-peer mesh messaging. In his session at @ThingsExpo, Ryan Bagnulo, Solution Architect / Software Engineer at SOA Software, focused on desi...
"At our booth we are showing how to provide trust in the Internet of Things. Trust is where everything starts to become secure and trustworthy. Now with the scaling of the Internet of Things it becomes an interesting question – I've heard numbers from 200 billion devices next year up to a trillion in the next 10 to 15 years," explained Johannes Lintzen, Vice President of Sales at Utimaco, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
"For over 25 years we have been working with a lot of enterprise customers and we have seen how companies create applications. And now that we have moved to cloud computing, mobile, social and the Internet of Things, we see that the market needs a new way of creating applications," stated Jesse Shiah, CEO, President and Co-Founder of AgilePoint Inc., in this SYS-CON.tv interview at 15th Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Gridstore™, the leader in hyper-converged infrastructure purpose-built to optimize Microsoft workloads, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Gridstore™ is the leader in hyper-converged infrastructure purpose-built for Microsoft workloads and designed to accelerate applications in virtualized environments. Gridstore’s hyper-converged infrastructure is the industry’s first all flash version of HyperConverged Appliances that include both compute and storag...
Today’s enterprise is being driven by disruptive competitive and human capital requirements to provide enterprise application access through not only desktops, but also mobile devices. To retrofit existing programs across all these devices using traditional programming methods is very costly and time consuming – often prohibitively so. In his session at @ThingsExpo, Jesse Shiah, CEO, President, and Co-Founder of AgilePoint Inc., discussed how you can create applications that run on all mobile devices as well as laptops and desktops using a visual drag-and-drop application – and eForms-buildi...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
Code Halos - aka "digital fingerprints" - are the key organizing principle to understand a) how dumb things become smart and b) how to monetize this dynamic. In his session at @ThingsExpo, Robert Brown, AVP, Center for the Future of Work at Cognizant Technology Solutions, outlined research, analysis and recommendations from his recently published book on this phenomena on the way leading edge organizations like GE and Disney are unlocking the Internet of Things opportunity and what steps your organization should be taking to position itself for the next platform of digital competition.
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at @ThingsExpo, Andrew Bolwell, Director of Innovation for HP's Printing and Personal Systems Group, discussed how key attributes of mobile technology – touch input, sensors, social, and ...