Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Weblogic

Weblogic: Article

Struts and J2EE

Struts and J2EE

Struts is a framework provided by Apache, designed to handle the presentation layer of your J2EE applications. The J2EE blueprints recommend that you use a Model 2 approach for your presentation layer, and Struts does just that for you. It doesn't try to re-create what is already available, nor is it unnecessarily complex. In fact, it leverages other J2EE technologies you may already know, like servlets, JSP, and JavaBeans, to provide a flexible presentation layer at a minimal cost. Best of all, when you write an application with Struts you'll find that it is easy to maintain and easy to extend because you used a framework rather than just hacking out tons of completely unrelated JSP pages.

The Model 2 pattern, also known as the model, view, controller (MVC) pattern, consists of three components (see Figure 1). The first is a "model," which is an object that represents your data and the state of your application; this object has no need for any logic, it just contains data. The second component is a "view," which is simply a presentation of the data to the user. The view does not change the data directly; it marshals data from the model to the user interface, or it sends user input to the controller. The controller is usually the most complex component of the three. It is responsible for receiving input from the user interface (UI), and for changing the data in the model. Beyond that the controller is where your logic resides, and can control many aspects of an application based on the model data and the user input.

If this paradigm isn't clear to you or seems a bit complex, just read on. In the next few paragraphs you'll see that it's really quite simple. Our example will be a simple form to change a password written with Struts.

Let's start with the model. The Struts component that implements a model is the ActionForm (see Listing 1). It's just a JavaBean with two additional methods. The first is the validate method, which performs simple validation on the data such as the string comparisons, or checking for required values here. The reset method initializes your form.

You may have noticed that over half the code in this simple three-variable form consists of accessors (getter methods) and mutators (setter methods). Struts 1.1 contains features that can help you rid yourself of this redundant code. Instead of extending ActionForm, just extend DynaActionForm. The DynaActionForm contains getters and setters for your data in the form of get(String) and set(String, Object). DynaActionForm also inherits the reset() and validate() methods so you can simply code them normally.

If you want to get rid of your ActionForm class altogether, Struts 1.1 contains a validator plug-in that will allow you to map validation rules to fields via XML configuration files. You can use predefined rules provided by Struts, or even write your own. The validator is actually from the Apache commons project, and was pulled into Struts to satisfy the need for validation without the code. For the sake of brevity I will not go into the details of the validator here. After all, my form is so simple I just want my validation method to verify that the passwords match. Suffice it to say that if you need to perform a validation that is already provided by Apache, it's the way to go.

The second component is the view. You can write this component simply by using JSP, but Struts offers much more for you to use in the view. There are six taglibs provided by Struts: html, logic, bean, nested, template, and tiles. Your bread-and-butter taglibs are html (obviously), bean, and logic (see Listing 2).

Each element of the html library will render html. The errors tag will print out an error to the screen. For example, if your ActionForm fails validation the ActionErrors returned will be printed out here.

The forms "form" tag starts a form and the action attribute matches the action element of an html form, except in this case you want to post to your controller, called an Action. The other html tags here are basic text fields and password fields. When they are rendered the values of their respective ActionForm properties are placed in the fields, and their input will be mapped automatically to your ActionForm properties. Remember that the ChangePasswordActionForm is also a bean so you can use the bean library to access it. If you want to perform some special manipulation of the data, rather than using scriptlets you can use the logic library, which will let you iterate through lists and control blocks with easy-to-read JSP tags. Take note though that your view should contain only presentation logic, nothing more.

There is also another plug-in for the view, called the tiles plug-in. It allows you to create reusable "tiles" and layout "tiles" in JSP. Imagine being able to make a "BorderLayout" tile. Then include your header tile NORTH, and your footer tile SOUTH, by default. Each specific page overrides CENTER. I happen to like this plug-in, but it also requires its own configuration files and a lot more detail. I recommend you look at it, but hold off until your second Struts application.

The third component is the controller. With a Struts application you have two controllers. The "true" controller of the application is the ActionServlet, provided by Struts in the form of a servlet. This servlet is configured with an XML file that tells Struts how to map your action forms to JSP pages to Action classes. That configuration, however, cannot possibly contain all of the possible submissions and appropriate reactions. Since your users are going to input dynamic data, you need to write a class, which extends Action to handle that input. Your action works with the action servlet to control the application.

The action servlet is like an air traffic control center - it controls everything. The action class is like an airplane passing through the control center's air space. The plane has a destination, but it cannot get there without the control center. Conversely, the control center won't have anything to do without a plane to direct. It looks at the plane's destination and based on where it's located (its state), it may send the airplane along or it may tell it to land. Listing 3 is an example action.

The only method you have to write is the execute method (called the "perform" method in Struts 1.0). This method returns an ActionForward, which is also defined in the XML configuration file. The ActionForward tells the action servlet where to direct the application to next. It allows you to redirect the user, based on user input, and it places the destination outside the code, again in the XML configuration file, so we can easily make changes to the application without recompiling anything.

The Action is where your application logic should exist. It is also where Struts meets your EJBs, messaging queues, JDOs, and so on. The trick here is to keep it simple. My changePassword method may contact the local LDAP, a session bean, or an application-specific database. Just put it in another method, or if there is a great deal of business logic being performed here, put it in another business object.

Now that you have your three components, I'll show you how they all fit together. It's all in the Struts configuration file. When you set up the action servlet the typical mapping is to "*.do". The only required parameter is "struts-config". This parameter should name where your XML configuration file is, such as "WEB-INF/struts-config.xml". There are also three other variables I recommend you set initially. Validate=true will turn on validation for your XML configuration file, so you will know if you put something incorrect into it. Debug=true and detail=2 will turn on a good deal of debugging information so you can see what the application is doing. These are good for development, but once your app is ready for production there you will probably want to turn them off (see Listing 4).

The configuration file contains several elements: action mappings, message resources, form beans, forwards, plug-ins, and datasources. This is where you define your forwards and loosely couple all of your components. Don't underestimate the configuration though. The components you have to write are pretty simple, but all it takes is one little typo in your configuration file, to keep it from deploying properly. Rather than editing this file by hand I recommend you use a tool such as the "Struts Console" by James Holmes at www.jamesholmes.com/struts (see Figure 2). It will help get your configuration files together quickly, and make maintenance easier too. It works with both Struts 1.0 and 1.1 dtds, and it will even create tiles and validation and tiles XML files. Most important, it will help you avoid having to waste your valuable time finding a simple mistake in an XML file.

There really isn't much left for you to do. The framework is written for you, and is probably more than flexible enough to suit your needs. All you have to do is write a few lightweight components, set up your configuration file(s), wrap it all up in a war, and deploy it. Stick with the 1.0 features for your first few forms. Once you are comfortable with those you can add in some of the 1.1 features if you desire.

Conclusion
The more you use a framework like this the more you'll appreciate it. Here all of the repetitive parts of your navigation, validation, and display are already written for you. The applications using the framework are easy to maintain and to extend. You can use it to easily lay a Web front end on top of your J2EE infrastructure. You will have to spend a little time up front to learn the framework, but the payoff is worth it. Once you know the framework, you will be able to rapidly create applications that use it, and because of the bump you get in productivity you'll want to use it again.

More Stories By Aristotle Allen

Aristotle Allen is a Senior Development Analyst at PJM Interconnection LLC. Ari has worked in high-tech manufacturing, an ASP and utilities and chooses to specialize in Java, especially J2EE. [email protected] / http://aballen.phathookups.com

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.


IoT & Smart Cities Stories
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
The Founder of NostaLab and a member of the Google Health Advisory Board, John is a unique combination of strategic thinker, marketer and entrepreneur. His career was built on the "science of advertising" combining strategy, creativity and marketing for industry-leading results. Combined with his ability to communicate complicated scientific concepts in a way that consumers and scientists alike can appreciate, John is a sought-after speaker for conferences on the forefront of healthcare science,...
Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
DXWorldEXPO LLC announced today that Ed Featherston has been named the "Tech Chair" of "FinTechEXPO - New York Blockchain Event" of CloudEXPO's 10-Year Anniversary Event which will take place on November 12-13, 2018 in New York City. CloudEXPO | DXWorldEXPO New York will present keynotes, general sessions, and more than 20 blockchain sessions by leading FinTech experts.
Apps and devices shouldn't stop working when there's limited or no network connectivity. Learn how to bring data stored in a cloud database to the edge of the network (and back again) whenever an Internet connection is available. In his session at 17th Cloud Expo, Ben Perlmutter, a Sales Engineer with IBM Cloudant, demonstrated techniques for replicating cloud databases with devices in order to build offline-first mobile or Internet of Things (IoT) apps that can provide a better, faster user e...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of ...