Monday, August 4, 2008

Struts and WebSphere: What does Struts do? How does Struts and J2EE Work?

1

Struts and WebSphere

Well, here's a bad way to start off a book about Struts: Struts isn't that great.

Now don't get me wrong, it's a fantastic framework, it is incredibly pervasive, and it will make many of the routine tasks you really hate doing a little bit easier, but it won't revolutionize the way you program.

So, what does Struts do? Well, Struts solves problems. It doesn't solve every problem, but it does address a few problems that arise over and over again in our J2EE applications.

First of all, Struts provides a great mechanism for handling user input. Struts makes it very easy to validate any data a user might have typed into a form and submitted to the server. Form handling and input validation is always a stabbing pain in the neck. The Struts framework provides a fantastic form validation mechanism that reduces this stabbing pain to a much more tolerable throbbing sensation.

Secondly, Struts provides a relatively simple mechanism for providing feedback to a user. Not only does Struts help weed out bad input data, it also provides a mechanism for telling the user what it is they did wrong, so they can resubmit their form with something different filled out wrong.

Furthermore, if your user's preferred language is German, it would be nice to send error messages back to your user in German. Actually, always sending error messages back to users in German isn't a bad idea in itself. Instructions always seem so much more authoritative when relayed in Deutch. But the point is, Struts provides some great facilities for internationalizing your applications as well - not just error messages, but every single text string in your application.

Now don't get overly excited by this whole internationalization thing. Struts will do internationalization, but it does not do translation. Struts is not a translation server. If you have written your application in English, you will still have to hire a French linguist to translate the whole site so it can be understood by les Quebecois. You'll also have to have it all translated into Spanish so it can be read by Americans. Struts doesn't do translations, but it will recognize the preferred language of the client, and send appropriately translated text back to the client.

Struts also forces the developer to use good MVC, or as it’s affectionately know, Model View Controller. We’ll get into MVC later, but suffice to say, MVC is simply a darned good best practice, and Struts makes sure your developers stick to it.

Struts even provides a few neat custom tags that help the developer generate HTML to send to the client. The Struts custom tags become especially handy when generating HTML pages that include internationalized error messages. Other logic custom tags exist as well, although in my personally opinion, the Struts logic custom tags can be as aggravating as the scripted Java code they are intended to replace.

The latest incarnation of the Struts framework, version 1.1, introduces a fantastic new element called Tiles. While much of the Struts framework deals with controlling the flow of your application, Tiles provides some fantastic features for assembling complex web pages from much smaller html and jsp snippets. The Tiles portion of the Struts framework provides a sweet mechanism for assembling web pages that quite simply was lacking in earlier versions.

Struts also provides features for handling database connection pools. This facility was quite helpful back in the dinosaur ages when application servers didn't provide robust connection pooling services, but if you're deploying to WebSphere or any other J2EE compliant application server, using the Struts connection pooling services will only cause you problems. Stay away from them.

So, here's what Struts does:

-helps with input validation

-helps provide user feedback

-helps internationalize our applications

-enforces a good MVC design pattern

-provides a collection of semi-useful custom tags

-facilitates html development through Tiles

-provides a common framework

So, that's it. Struts doesn't write any code for you. It doesn't solve your performance problems. It isn't a rapid development environment. But Struts does address five or six very specific areas of application development that are often done poorly and inconsistently. By addressing issues such as form validation, error feedback and internationalization, Struts allows developers to concentrate on the more pressing aspects of application development.


Well, here's a bad way to start off a book about Struts: Struts isn't that great.

Now don't get me wrong, it's a fantastic framework, it is incredibly pervasive, and it will make many of the routine tasks you really hate doing a little bit easier, but it won't revolutionize the way you program.

So, what does Struts do? Well, Struts solves problems. It doesn't solve every problem, but it does address a few problems that arise over and over again in our J2EE applications.

First of all, Struts provides a great mechanism for handling user input. Struts makes it very easy to validate any data a user might have typed into a form and submitted to the server. Form handling and input validation is always a stabbing pain in the neck. The Struts framework provides a fantastic form validation mechanism that reduces this stabbing pain to a much more tolerable throbbing sensation.

Secondly, Struts provides a relatively simple mechanism for providing feedback to a user. Not only does Struts help weed out bad input data, it also provides a mechanism for telling the user what it is they did wrong, so they can resubmit their form with something different filled out wrong.

Furthermore, if your user's preferred language is German, it would be nice to send error messages back to your user in German. Actually, always sending error messages back to users in German isn't a bad idea in itself. Instructions always seem so much more authoritative when relayed in Deutch. But the point is, Struts provides some great facilities for internationalizing your applications as well - not just error messages, but every single text string in your application.

Now don't get overly excited by this whole internationalization thing. Struts will do internationalization, but it does not do translation. Struts is not a translation server. If you have written your application in English, you will still have to hire a French linguist to translate the whole site so it can be understood by les Quebecois. You'll also have to have it all translated into Spanish so it can be read by Americans. Struts doesn't do translations, but it will recognize the preferred language of the client, and send appropriately translated text back to the client.

Struts also forces the developer to use good MVC, or as it’s affectionately know, Model View Controller. We’ll get into MVC later, but suffice to say, MVC is simply a darned good best practice, and Struts makes sure your developers stick to it.

Struts even provides a few neat custom tags that help the developer generate HTML to send to the client. The Struts custom tags become especially handy when generating HTML pages that include internationalized error messages. Other logic custom tags exist as well, although in my personally opinion, the Struts logic custom tags can be as aggravating as the scripted Java code they are intended to replace.

The latest incarnation of the Struts framework, version 1.1, introduces a fantastic new element called Tiles. While much of the Struts framework deals with controlling the flow of your application, Tiles provides some fantastic features for assembling complex web pages from much smaller html and jsp snippets. The Tiles portion of the Struts framework provides a sweet mechanism for assembling web pages that quite simply was lacking in earlier versions.

Struts also provides features for handling database connection pools. This facility was quite helpful back in the dinosaur ages when application servers didn't provide robust connection pooling services, but if you're deploying to WebSphere or any other J2EE compliant application server, using the Struts connection pooling services will only cause you problems. Stay away from them.

So, here's what Struts does:

-helps with input validation

-helps provide user feedback

-helps internationalize our applications

-enforces a good MVC design pattern

-provides a collection of semi-useful custom tags

-facilitates html development through Tiles

-provides a common framework

So, that's it. Struts doesn't write any code for you. It doesn't solve your performance problems. It isn't a rapid development environment. But Struts does address five or six very specific areas of application development that are often done poorly and inconsistently. By addressing issues such as form validation, error feedback and internationalization, Struts allows developers to concentrate on the more pressing aspects of application development.

Creating a J2EE Project and Web Module

1. Once the WSAD has started, from the menu select File à New à Enterprise Application Project.

2. You will be asked if you wish to create a J2EE 1.2 or J2EE 1.3 compliant application. Pick your poison, but I'm going with a J2EE 1.3 project.

Click ‘Next >’

3. Your application needs a name.

I'm going to call mine PulpJava, after my fabulous website.

Resist the temptation to click finish. We may have established an ear, but we still need to add our web module.

Click ‘Next >’

NOTE: when we add a web module, the word 'Web' will be appended to the end of your application name, so mine will be called PulpJavaWeb. If you named your enterprise project, say, StrutsWeb, then your web module would be StrutsWebWeb. Now that'll work fine, but it'll look stupid. Always try your best not to look stupid.

At this point, you have an enterprise application, but you don't have any web or ejb modules associated with it.

4. To add a little spice to your application, click the New Module button.

Magically, after hitting the 'New Module' button, the WSAD asks to create four new modules, a client, EJB, web and connector module. We only want a web module.

5. Deselect the checkboxes next to every project option except "Web module." Look to the diagram for further clarification.

Notice the name of the Web Project is PulpJavaWeb.

Click ‘Finish’

NOTE: Whenever you're learning, I always suggest clicking every button on the screen and see what flies. Think outside of the box and explore!

However, in this situation, it is very important NOT to select the EJB project option. There's a little quirk with the spec that says every EJB module must have at least one EJB in it. If it doesn't, it won't deploy properly. As a result, if you create an EJB project, but do not add an EJB to it, your application, which includes your web module, won't run.

This can be a frustrating problem to troubleshoot. But bear this warning: if you're not going to immediately create an EJB, which we are not going to do, do NOT create an EJB module.

After clicking 'Finish' on the New Module Project window, you won't actually be finished. To be finished, you must again click the Finish button, although this time it is the 'Finish' button on the "EAR Module Projects" window.

6. Click the ‘Finish’ button to create your enterprise application and web module.

If clicking 'Finish' twice seems confusing or strange, it is because you are confused and strange. Clicking 'Finish' twice to complete a task makes perfect sense, and I'm surprised it isn't seen in applications more often.

7. Explore your project in the J2EE Hierarchy view.

From the J2EE Hierarchy view of the J2EE perspective, looking under the ‘Enterprise Applications’ directory, you can see that one J2EE project named PulpJava that contains a web module named PulpJavaWeb.


Switching Perspectives

A perspective is simply a combination of views and editors that together create an environment that facilitates a specific segment of application development.

Web based resources are most easily edited in the Web perspective.

1. To open the Web perspective, from the menu, select Window à Open Perspective à Other…

2. Scroll down in the ‘Select Perspective’ window and highlight ‘Web’

While you’re scrolling, notice all of the perspectives available, including Java, J2EE, XML and Data to name just a few.

3. With ‘Web’ highlighted, click ‘OK’ to open the Web perspective.

Notice how a globe appears along the left hand side of the WSAD. This is the ‘Perspectives Taskbar,’ which allows you to switch easily between various perspectives.


Adding Views to a Perspective

Perspectives are a combination of helpful views and editors that are intended to help you edit and maintain a particular resource. However, sometimes a view you love won’t appear on a particular perspective.

Any view can be added to perspective. Let’s make sure the ‘Project Navigator’ appears in the current perspective.

1. From the menu, select Window à Show View à Project Navigator

The ‘Project Navigator’ will appear as a tabbed window somewhere on your perspective.

You can now save your perspective with the extra view added.

2. From the menu, select Window à Save Perspective As…

3. Provide a name for your new perspective and click ‘OK’

After customizing and saving a perspective, you can reopen that perspective any time in the future.


Adding Struts Support to a Web Module

J2EE web modules support the Servlet and JSP APIs, but they do not automatically support the Struts framework.

The WSAD provides a very useful wizard that adds struts support to an existing web module.

1. From the ‘Project Navigator’ view of the Web perspective, right click on on the PulpJavaWeb module and select Properties.

Make sure you are right clicking on the web module, as the PulpJava (minus the word Web) project will have different properties from the web module.

In the properties Window, you will see a number of configurable options, including Java Build Path, JavaDoc Location and even a special Struts option. Suprisingly though, in order to add Struts support to a project, you do not go to the struts option. Go figure.

2. In the left hand side, click ‘Web Project Features.’

3. In the workpane on the right, click the checkbox next to Add Struts Support and then click Apply.

4. Accept the default settings, which includes the option to use Struts 1.1, and click Finish. This takes you back to the Properties window for the Web project.

5. Click ‘OK’ to exit the properties window and return to the WSAD.


Explore Struts Support in the Web Module

In the Project Navigator window, open the PulpJavaWeb project and explore its contents.

Under Java Source, note the package named com.ibm.pulpjavaweb.resources and its corresponding file, named ApplicationResources.properties. This is the property file used to hold internationalized text strings.

Open the web content folder and the WEB-INF folder as well and note the various tld, xmi and xml files.

The tld files describe the Struts custom tag libraries.

The xmi files represent IBM specific binding and extensions.

The two xml files are the web.xml file, required by any J2EE web application, and the struts-config.xml file, which is needed by the Struts framework.

These files represent the guts of our Struts based application, and will undoubtedly cause us no end of grief in the future.


Double-click on the web.xml file to open the deployment descriptor editor for the web module.

From there, click on the Servlets tab and take a gander at the single, monolithic Servlet that has been added to your application.

This single servlet, named action, that has been added is an instance of the Sruts ActionServlet.

Click on the action Servlet to display the various associated properties.

A struts application has one Servlet. This one Servlet, the ActionServlet, is responsible for handling every web based request that comes into the Struts application.

Yes, one Servlet to rule them all.

And while you're looking at this ActionServlet, look at the URL mapping for the ActionServlet: *.do

This mapping means that any request that comes to the server that ends in with the three characters ".do" will be sent to the ActionServlet. So, if types into the address bar of their browser:

http://www.pulpjava.com/PulpJavaWeb/login.do

the ActionServlet will handle and appropriately process that request.


Locating the struts-config.xml File

You may be wondering: “how does the ActionServlet know how to handle the millions of requests that it is being bombarded with?”

Well, as programmers, we code these special Struts components called Action objects. The ActionServlet takes a web based request and maps it to an appropriate action class. It knows how to do this by reading the struts-config.xml file.

Open the struts-config.xml file

1. From the ‘Project Navigator’ view of the Web perspective, open the PulpJavaWeb project, open the ‘WebContent’ folder, and then open the ‘WEB-INF’ folder.

2. Under the ‘WEB-INF’ folder, double click in the struts-config.xml file to open the struts-config editor.

3. Explore the various tabs of the struts-config.xml editor. Look at the ‘Source’ tab and look at all the sad, empty elements that a good Struts application will amply populate.

The ActionServlet and the struts-config.xml file go together like sex and litigation. If you look at the ActionServlet entry in the web.xml file, you'll notice that there is an initialization parameter named 'config,' and it is associated with the 'struts-config.xml' file. When the ActionServlet first loads, it reads the struts-config.xml file and configures itself appropriately.


Working with Struts

Before we can jump into creating our first Struts application, we must establish a baseline of understanding with regards to how the Struts framework works. Earlier discussion of the ActionServlet has broached this topic.

A Struts application works like this:

First, all client requests go through the ActionServlet. We don’t code the ActionServlet, although we do code these things called Action classes, which the ActionServlet is responsible for invoking.

The big question is, given a request, how does the ActionServlet know which Action class to invoke?

Well, the ActionServlet uses the struts-config.xml to map a client request to an appropriate Action object. For example, the struts-config.xml file might contain an entry such as this:

type="com.pulpjava.action.RegisterAction">

According to this entry, if a client calls the ActionServlet with a URL that ends with /register.do, the ActionServlet will invoke the RegisterAction.

Action objects have a method called execute, or perform if you’re still coding in Struts 1.0. The execute of perform method contains the logic needed to handle the clients request. The execute method of the Action class is where the developer places their code.

Towards the end of the execute method of the Action class, after the business logic required to handle the request is completed, the developer is responsible for figuring out which JSP should be called to generate a web page to be displayed in the clients browser.

The return type of the execute method is something called an ActionForward, which simple put, represents a web page we are interested in forwarding the client. When the web page is sent back to the client device, the request – response cycle is completed.

Let's create a simple Struts application that figures out which language a client speaks, and send them to an appropriate JSP page.


Creating Java Server Pages

The final task of an Action object is to decide what type of a web page, usually an html or jsp, will be returned to the client. We are going to put the cart before the horse by creating our jsp pages before we create our Action.

Our Action class is going to check the preferred language of the client, and send them to an appropriate web page. We’re only going to concern ourselves with French, English, and Spanish speaking clients, demonstrating a general disregard for all other languages.

1. From the ‘Project Navigator’ view of the Web perspective, right click on the WebContent folder and from the context menu, select New à JSP File

2. For the name of the file, enter englishspeaker.jsp

3. Click ‘Finish’ to create the jsp file.

Page Designer, a WYSIWYG editor will appear. Treat Page Designer just like you would Microsoft Word or any other visual editor.


4. Delete the default text “Place content here.” and then add your own text. Something witty about the user speaking English.

5. Press CTRL+S or do a File à Save All to save your changes.

An asterix appears in the editor tab of any unsaved files. When a file is saved, the marking goes away.

6. Create a second and third jsp page, one being creatively called spanishspeaker.jsp and the other called frenchspeaker.jsp.

7. Add witty comments about the French and Spanish languages in the corresponding jsp files.

8. Save your files using a FileàSave All from the menu.

NOTE: Make sure these three files, englishspeaker.jsp, frenchspeaker.jsp and spanishspeaker.jsp, are under the WebContent folder.

It isn't good enough for these files to simply be close to the WebContent folder.

Do not create fancy little subdirectories under the WebContent folder. You can get fancy later. If you want this exercise to work, make sure the three files are under the WebContent folder.

Now, which folder are your three JSP files under?

Once you have saved your JSP files, you are ready to move onto the next step, creating the Action class.

No comments: