Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Expo on Google News


2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
Top Links You Must Click On


Java Feature — Bringing Together Eclipse,WTP, Struts, and Hibernate
Bringing Together Eclipse,WTP, Struts, and Hibernate

In the article "Creating Web Applications with the Eclipse WTP" (http://jdj.sys-con.com/read/152270.htm ), we created a Web application using Eclipse Web Tools Project, the Tomcat application server, and the MySQL database server. That application (DBTest) was good, however, it had some limitations:

  1. Java Server Pages (JSP) names were hard-coded inside the servlet code
  2. SQL was also hard-coded in the command classes
Fortunately, two interesting solutions can address these problems. The first problem can be addressed using the Open Source Struts framework, which separates an application's Model, View, and Controller by mappings the actions of the model to view components (such as JSPs) in a simple configuration file.

The second problem can be addressed by using one of the frameworks providing persistence between the Java world and the relational database world. Hibernate framework provides a powerful high-performance mapping engine between the objects and database tables. The following technology is used in this article:

  1. J2SE 5.0 JRE: http://java.sun.com/j2se
  2. Eclipse 3.1: www.eclipse.org
  3. WTP 1.0: www.eclipse.org/webtools
  4. Tomcat 5.0: http://jakarta.apache.org/tomcat/
  5. MySQL 4.0.25: www.mysql.com
  6. MySQL Connector/J driver 3.1: www.mysql.com/products/connector/j/
  7. Struts 1.1: http://struts.apache.org
  8. Hibernate 3... www.hibernate.org
Application Overview
Let's recap what we did last time. It was a basic Web application that implemented the following use cases:
  • Customers have to register on the site to place orders
  • Customers can place orders
  • Customers can view their orders
  • Admin can list all registered customers
The system was implemented using the generic servlet/JSP programming model and the MySQL database, with Tomcat application server. Two classes, Customer and Order, represented the domain model of the system (see Figure 1).

Two corresponding database tables CUSTOMERS and ORDERS were created to represent the data that were held in these objects. We also created four database command classes that were responsible for performing the aforementioned use cases, and four servlets acting as controllers to gather input from the user, invoke these commands, and forward the response to the appropriate JSP. A special class CommandExecutor was responsible for handling the database connections using Tomcat connection pools.

Adding Struts Support
Import the DBTest.WAR file (http://java.sys-con.com/read/152270.htm) into your Eclipse workspace using the File-Import option and selecting the WAR file item to import. That will work perfectly if the DBTest project isn't already in your workspace. If DBTest project is already in your workspace, just copy it to preserve the existing project by right-clicking on the project in the Navigator view and selecting Copy and then Paste when you'll be prompted for the new project name (we'll select DBTestStruts as the new name), so that the existing project isn't clobbered. Now to add Struts support, we have to copy the following files into the WEB-INF\lib folder: struts.jar, commons-lang.jar, commons-collections.jar, commons-beanutils.jar, commons-validator.jar, commons-logging.jar, commons-digester.jar, commons-fileupload.jar.

All these files can be downloaded from the Struts Web site and contain the Struts framework along with corresponding Apache Commons packages necessary for handling features such as internationalization, collection operations, utilities, validation, logging, digester, and file upload operations. They are all supporting parts for Struts. We won't use all of these features here, but Struts relies on many of them (e.g., the digester part is heavily used when parsing a Struts configuration file), and they may become handy later when services such as logging and file uploading are required.

So add the following files to the WEB-INF folder: struts-config.xml, struts-bean.tld, struts-html.tld, struts-logic.tld, struts-nested.tld, struts-template.tld, struts-tiles.tld.

The most important of these files is struts-config.xml, which is a main configuration file for the Struts framework. It contains definitions of all the action mappings, data sources, plug-ins, etc. See the sample one in Listing 1.

TLD files are Struts tag library definition files that can be used inside of JSPs to do various useful operations such as HTML rendering, logic handling, or Tiles support. They can be obtained from the Struts 1.1 distribution.

The next thing we need to do is modify our Web Deployment Descriptor (web.xml) to specify the location of the Struts configuration servlet and corresponding parameters. The code snippet from Listing 2 should be added to web.xml.

Tags from Listing 2 define the location of the Action Servlet, which is the Struts primary controller responsible for handling the lifecycle of the actions and mapping them to forwards, which are objects that are returned by an action and have two fields: a name and a path (typically the URL of a JSP file). The location of the struts-config.xml file is specified here, as well as the parameters for debugging and validation. The servlet is loaded at startup and the order of its load is 1 (first servlet to be loaded). The servlet gets invoked whenever a *.do pattern is detected in the invoking URL.

Now we have to convert our existing servlet classes into action classes and define appropriate mappings for them in struts-config.xml. To simplify this process, we'll provide an abstract superclass for all of our actions (see Listing 3) (Listings 3-15 and additional source code can be downloaded from the online version of this article.)

In this class, we provide implementation of the "execute" method that's invoked by default on the action by the Struts 1.1 framework. It handles the logic in its performAction() method and then forwards to either success or failure processors depending on whether an exception has been thrown or not. Correspondingly, mappings for both success and failure will have to be defined in the Struts configuration file (struts-config.xml) for every action.

Creating concrete actions is easy. We can use the Eclipse wizard to create action classes. Make sure that AbstractAction is selected as a superclass and the "Inherited abstract methods" box is checked (see Figure 2).

The class CreateCustomerAction with performAction() method will be automatically generated. Copy the contents of the CreateCustomerServlet doGet() method (see previous article at http://java.sys-con.com/read/152270.htm -) and paste it into performAction() with the modifications shown in Listing 4.

As one can see, the only difference between non-Struts code and Struts code is that instead of the following code:

RequestDispatcher rd = getServletContext().getRequestDispatcher("/customer_created.jsp");
       rd.forward(request, response);

the following (simpler one) is used:

return mapping.findForward("customer_created");

We don't have to hard-code the name of the JSP inside our code any more. Instead, we use the "customer_created" reference, which will be resolved in the struts configuration file. Inside the <action-mappings> tags, we'll add the fragment in Listing 5.

In this example, /CreateCustomer would be the URI to invoke the action. Two forwards are defined - "customer_created" - which, incidentally, points to "customer_created.jsp" and "failure," which points to "failure.jsp" where errors can be displayed. It's useful to have a common error page for the application, and we'll create one right now (see Listing 6).

In this file, we use the Struts HTML tag library to display the errors captured.

In a similar manner, we'll convert other servlets into Struts actions. Don't forget to change the URLs in the index.html file and other JSP files and add a suffix ".do" to the action invocations. Changing references from DBTest to DBTestStruts is also necessary to deploy the new application in co-existence with the old one in the Tomcat server. Also change the display name in web.xml from DBTest to DBTestStruts.

Remove the old servlet definitions from the DBTest application source code and Web Deployment Descriptor - all we need there is just the definition of our Actions and the Action servlet. To delete the "servlet" package, simply right-click on the "servlet" package and select "Delete," then answer, "Yes," when prompted for confirmation.

To deploy the new application to Tomcat open its console http://localhost:8080/manager/html and deploy a new WAR file. Make sure that DBTest.xml is copied into DBTestStruts.xml and all the references to DBTest are changed to DBTestStruts in it.

Another issue, however, is that in the original solution's SQL was hard-coded directly inside the command classes. This will be addressed in the next section by the popular Hibernate framework, which supports persistence between Java and relational databases.

Adding Hibernate Support
The Hibernate framework helps you in the following areas:

  1. Object-relational mapping. It allows you to seamlessly map Java objects and the relationships between various classes into database tables and the relationships among them. This is done using XML configuration files and saves a lot of the time that developers spend coding custom SQL queries and constructing objects from JDBC result sets.
  2. Connection management. Reusing existing database connections is one of the most important efficiency tuning mechanisms.
  3. Transaction management. The ability to start, commit, and rollback transactions when necessary. It will also support XA transactions and two-phase commits as long as you use the JDBC driver and a data source capable of XA.
To use Hibernate in our application download the latest version (currently 3.0) of the Hibernate framework. Then unzip it and add hibernate3.jar into our application's WEB-INF\lib directory. This automatically adds this JAR file to the application's build time and runtime class-path according to the J2EE standards. You also have to add dom4j.jar to WEB-INF\lib, which is also available from the Hibernate Web site. This is necessary to include the XML parser support needed for Hibernate configuration files.

Now we have to configure Hibernate on the application level. Create the hibernate.cfg.xml configuration file under "Java Source" folder in Eclipse: this way when the application is deployed it will automatically go into the application class-path under WEB-INF\classes.

The file shown in Listing 7 contains references to the following:

  1. The JDBC data source reference. Note that we have to use a fully qualified reference - java:comp/env/jdbc/TestDB.
  2. The request to show the generated SQL in the Java system console where System.out messages go.
  3. The SQL dialect to be generated. We use the MySQL database.
  4. The reference to the file that contains the mapping between domain classes and database tables.
The separate file, hibernate.mapping.xml, contains the mapping information between domain objects (entities) used in the application and the corresponding relational tables. This file should be colocated in the same directory with hibernate.cfg.xml under the Java Source.
About Boris Minkin
Boris Minkin is a Senior Technical Architect of a major financial corporation. He has more than 15 years of experience working in various areas of information technology and financial services. Boris is currently pursuing his Masters degree at Stevens Institute of Technology, New Jersey. His professional interests are in the Internet technology, service-oriented architecture, enterprise application architecture, multi-platform distributed applications, and relational database design. You can contact Boris at bm@panix.com.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Reading this:
"// This abstract class overrides Struts action class execute method and provides abstract
// performAction method to be overwritten by sub-classes. This helps us isolate some
// common error processing into one place, rather than having it several places in the
// sub-classes."
I don't really see how handling the errror in the AbstraAction class simplify error handling the subclasses.
In errors.add("name", new ActionError("id")); the value & key pair are different from what we have in subclasses.

Hello,
Could you please tell me how this dbtest worked?
As I tried following the article but was lost when
it spoke of the different classes I did not know what these classes should contain and how they communicate with each other.
Thank you for your help

Hi,

I got an error trying to uncompress the .war file, it seems that it's broken.

SEVERE: Exception fixing docBase: {0}
java.util.zip.ZipException: error in opening zip file

Lucas.

Some users have complained about corrupted .war file.
Here is a link to the good one:
http://www.panix.com/~bm/DBTestSH.war

The war file is corrupted

I think the war file is corrupted. regards Mark

The provided DBTestSH.war is a corrupted one. You can not unzip it. Please check.
Thanks!

In the article 'Creating Web Applications with the Eclipse WTP' (http://jdj.sys-con.com/read/152270.htm ), we created a Web application using Eclipse Web Tools Project, the Tomcat application server, and the MySQL database server. That application (DBTest) was good, however, it had some limitations

While it was nice to see you bring all of these technologies together (Struts, XML, Java, Hibernate, WTP, MySQL and it's connector). One has to ask; "But why is this necessary?". This represents 7 technology related fail points and 7 tools that a programmer needs a good familiarity with to be efficiently productive. This is way too many! Each additional tool adds extra cost to evaluating programmers to staff business level Java client/server application development positions and increases project risk. While I love Java, as a manager, this is a huge problem with it's use.

What I'd like to see a lot more of is POJO solutions to serious Web application development problems.

While its great that you can bring all of these tools together to solve a problem, it does little to address the fundamental flaw with Java (and several other languages) which is... Java is not really designed for Server/dumb client applications (which are Web apps.) and after 10 years have been spent kludging it to fit that round hole... here we are still trying to make a square peg round.

If I'm wrong, I'd be thrilled to admit it. But to prove me wrong you have to build a true business level Web app. with just Java, an IDE, a database engine and its aplicable connector, and any vanilla Web server engine you choose. That's it. No XML, no cocoon, jscript, Struts, nada, zip. Oh, one final condition... development time has to be within 15% of development with all those "assists". If this can't be done, then let's all stop fooling ourselves, find something that does, and leave Java to solve the other problems it is designed for and stop trying to fit it into the wrong type of hole.

While it was nice to see you bring all of these technologies together (Struts, XML, Java, Hibernate, WTP, MySQL and it's connector). One has to ask; "But why is this necessary?". This represents 7 technology related fail points and 7 tools that a programmer needs a good familiarity with to be efficiently productive. This is way too many! Each additional tool adds extra cost to evaluating programmers to staff business level Java client/server application development positions and increases project risk. While I love Java, as a manager, this is a huge problem with it's use.

What I'd like to see a lot more of is POJO solutions to serious Web application development problems.

While its great that you can bring all of these tools together to solve a problem, it does little to address the fundamental flaw with Java (and several other languages) which is... Java is not really designed for Server/dumb client applications (which are Web apps.) and after 10 years have been spent kludging it to fit that round hole... here we are still trying to make a square peg round.

If I'm wrong, I'd be thrilled to admit it. But to prove me wrong you have to build a true business level Web app. with just Java, an IDE, a database engine and its aplicable connector, and any vanilla Web server engine you choose. That's it. No XML, no cocoon, jscript, Struts, nada, zip. Oh, one final condition... development time has to be within 15% of development with all those "assists". If this can't be done, then let's all stop fooling ourselves, find something that does, and leave Java to solve the other problems it is designed for and stop trying to fit it into the wrong type of hole.


Your Feedback
Achille wrote: Reading this: "// This abstract class overrides Struts action class execute method and provides abstract // performAction method to be overwritten by sub-classes. This helps us isolate some // common error processing into one place, rather than having it several places in the // sub-classes." I don't really see how handling the errror in the AbstraAction class simplify error handling the subclasses. In errors.add("name", new ActionError("id")); the value & key pair are different from what we have in subclasses.
Mintara wrote: Hello, Could you please tell me how this dbtest worked? As I tried following the article but was lost when it spoke of the different classes I did not know what these classes should contain and how they communicate with each other. Thank you for your help
Lucas wrote: Hi, I got an error trying to uncompress the .war file, it seems that it's broken. SEVERE: Exception fixing docBase: {0} java.util.zip.ZipException: error in opening zip file Lucas.
Boris Minkin wrote: Some users have complained about corrupted .war file. Here is a link to the good one: http://www.panix.com/~bm/DBTestSH.war
karthik wrote: The war file is corrupted
mark wrote: I think the war file is corrupted. regards Mark
Jim wrote: The provided DBTestSH.war is a corrupted one. You can not unzip it. Please check. Thanks!
SYS-CON India News Desk wrote: In the article 'Creating Web Applications with the Eclipse WTP' (http://jdj.sys-con.com/read/152270.htm ), we created a Web application using Eclipse Web Tools Project, the Tomcat application server, and the MySQL database server. That application (DBTest) was good, however, it had some limitations
DH Allingham wrote: While it was nice to see you bring all of these technologies together (Struts, XML, Java, Hibernate, WTP, MySQL and it's connector). One has to ask; "But why is this necessary?". This represents 7 technology related fail points and 7 tools that a programmer needs a good familiarity with to be efficiently productive. This is way too many! Each additional tool adds extra cost to evaluating programmers to staff business level Java client/server application development positions and increases project risk. While I love Java, as a manager, this is a huge problem with it's use. What I'd like to see a lot more of is POJO solutions to serious Web application development problems. While its great that you can bring all of these tools together to solve a problem, it does little to address the fundamental flaw with Java (and several other languages) which is... Java is not really designe...
DH Allingham wrote: While it was nice to see you bring all of these technologies together (Struts, XML, Java, Hibernate, WTP, MySQL and it's connector). One has to ask; "But why is this necessary?". This represents 7 technology related fail points and 7 tools that a programmer needs a good familiarity with to be efficiently productive. This is way too many! Each additional tool adds extra cost to evaluating programmers to staff business level Java client/server application development positions and increases project risk. While I love Java, as a manager, this is a huge problem with it's use. What I'd like to see a lot more of is POJO solutions to serious Web application development problems. While its great that you can bring all of these tools together to solve a problem, it does little to address the fundamental flaw with Java (and several other languages) which is... Java is not really designe...
Enterprise Open Source Magazine Latest Stories . . .
Apache Deltacloud, the Red Hat-contributed ReSTful API that abstracts differences between clouds so services on any cloud can be managed – provided of course there’s a driver – has graduated from the Apache Foundation’s incubator and is now a full-fledged Top-Level Project (TLP). The...
With Cloud Expo 2012 New York (10th Cloud Expo) just four months away, what better time to start introducing you in greater detail to the distinguished individuals in our incredible Speaker Faculty for the technical and strategy sessions at the conference... We have technical and st...
AMD said late Tuesday that its chief sales officer Emilio Ghilardi had left the company and that CEO and president Rory Read is going to do his job while a replacement is sought. AMD didn’t say why Ghilardi left but it’s assumed Read wants his own people. Read is relatively new to th...
During the lifespan of M3 (Monitis Monitor Manager) there has always been something lacking – timers. M3 execution procedure was outlined in this previous article. The execution mentioned in the latter was a one-time-execution, whereas server monitoring requires periodic invocati...
Red Hat is putting its bought-in Gluster scale-out NAS storage technology, acquired in October, on the Amazon cloud. It’s styled Red Hat Virtual Storage Appliance for Amazon Web Services and other clouds are supposed to follow in short order.
A new episode of the screencast series is now available at the OpenNebula YouTube Channel. This screencast demonstrates the new easily-customizable self-service portal for cloud consumers. Its aim is to offer a simplified access to shared infrastructure for non-IT end users. The scree...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON Featured Whitepapers
ADS BY GOOGLE