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.

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.

@ThingsExpo Stories
Organizations do not need a Big Data strategy; they need a business strategy that incorporates Big Data. Most organizations lack a road map for using Big Data to optimize key business processes, deliver a differentiated customer experience, or uncover new business opportunities. They do not understand what’s possible with respect to integrating Big Data into the business model.
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they b...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
SYS-CON Events announced today that TidalScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Amazon is pursuing new markets and disrupting industries at an incredible pace. Almost every industry seems to be in its crosshairs. Companies and industries that once thought they were safe are now worried about being “Amazoned.”. The new watch word should be “Be afraid. Be very afraid.” In his session 21st Cloud Expo, Chris Kocher, a co-founder of Grey Heron, will address questions such as: What new areas is Amazon disrupting? How are they doing this? Where are they likely to go? What are th...
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...