Monday, August 4, 2008

Handling Forms with Struts and ActionForm Objects: Java Struts Development with Rational Application Developer/Architect IRAD for WebSphere

Creating HTML Pages and Forms

Our preliminary look at Struts demonstrates how the framework enforces a Model View Controller framework. Your Action class acts as the controller, your Java Server Pages act as the view, and somewhere inside the execute method of the Action class you create, you call on JavaBeans, which act as your model.

Another major feature of Strut is thre frameworks ability to validate input data from the user. To demonstrate these form handling facilities, lets modify our application so that rather than looking at the user’s locale object to determine their language preference, lets ask the user straight out using an html form.

Our first step in demonstrating the form handling and input validation facilities is creating an html page named language.html

1. Switch to the Web perspective WindowàOpen PerspectiveàWeb

2. In the ‘Project Navigator’ view, open the PulpJavaWeb project and right click on the WebContent folder

3. From the context menu that appears, select New à HTML/HTML File

4. In the ‘New HTML File’ wizard, enter language.html as the ‘File Name’ and click Finish

The registrationform.html file should open in the html editor. If it doesn't, just double-click on the language.html file in the Navigator view and it will open.

5. Delete the default text that reads "Place content here" and instead type in something creative like: "We want to know about you!"

Add a few carriage returns after the text you have written, and add a form element to your page.

6. To add a form element, from the menu, choose Insert --> Form and Input Fields --> Form

A dotted box will appear on your screen after you add the form.

Any information you wish to send to the server, be it from a textfield or a radio button, must be placed inside these dotted lines that delineate the form.

Since we'll be adding a textfield, I'd suggest throwing in a few carriage returns to give yourself more space with which to work.

7. Within the dotted box that delineates the form, add four or five carriage returns (Enter key).

8. We need to find out if the user prefers French, English or Spanish. So, inside the dotted lines that delineate the form, enter the text "What is your preferred language? French, English or Spanish?"

9. Move your cursor to a point following this text, and from the menu, click Insert --> Form and Input Fields --> Text Field. This will add a textfield to your page.

10. In the textfield wizard that appears, type, in all lower case letters, 'language' as the name of the text field and click OK.

Once your handsome text and textfield has been added, add a button to submit the form.

11. While still inside the dotted lines that delineate the form, move your cursor to a location after your textfields and select Insert --> Form and Input Fields --> Submit Button.

Enter SUBMIT for both the name and label of the button. Feel free to add a reset button as well.

NOTE that all textfields and submit buttons must be within the dotted lines that delineate the form. If they are not, your form won't work!

Calling an Action From a Form

So far we have created a form that contains one textfield named language, and a single submit button.

We want a user to enter their preferred language into the textfield and when the user clicks on the SUBMIT button, this information will get sent to our TryLingualAction.

To do this, we must edit the form, indicating that the action event of clicking the button on the form is to send all input data to the uri /tryLingual.do

In html, it looks like this:

We could just go into the source code of out html page and hard code this value in, but it’s a good exercise, if not an exercise in frustration, to use the Page Designer tool to point the form at our TryLingualAction.

1. Right-click on the dotted lines that delineate the form, and from the context menu that appears, select ‘Attributes’

If you can’t get the attributes of the form, instead, click on the textfield, which should make the properties of the textfield appear in the Attributes vew. From there, click the up arrow key a couple of times until you have toggled to the attributes of the form.

The 'Attributes' window will appear in the lower left hand corner showing the various configurable properties of the form.

The property of the form we are interested in is the 'Action'

2. Set the ‘Action’ attribute of the form to ‘tryLingual.do’

The action represents the destination of the client request when the submit button is clicked. When the user clicks the submit button on our form, we want their request to be routed through the ActionServlet to our TryLingualAction.


Obtaining Form Data

In our original TryLingualAction class, we determined the preferred language of the user by inspecting the users Locale object. We now want to get this information directly from the user through the html form.

The method to obtain information a user has typed into a textfield is:

request.getParameter(“language”);

Where the request is the HttpServletRequest passed to the execute method of the Action class, and “language” is the name given to the textfield on the html page.

<INPUT type="text" name="language" size="20">

We must replace the line of code in our TryLingualAction class that reads:

With a line of code that reads:

We will also have to make a slight change to our TryLingualAction class. We currently get the users language preference out of the Locale object. Instead, we want to grab that information from the form. Open the TryLingualAction class. From the Project Navigator view, open the Java Resources folder and then open the com.pulpjava.action package. Double-click on the TryLingualAction class and find the line of code that declares and initializes the String language.


Updating an Existing Action Class

1. Open to the Web Perspective

Windows à Open Perspective à Web

2. Open the PulpJavaWeb folder, open the ‘Java Resources’ folder and then open the package named com.pulpjava.action

3. Double-click on the TryLingualAction.java class under the com.pulpjava.action package

4. Comment out the line of code that obtains the users preferred language through the Locale object

//String language = request.getLocale().getDisplayLanguage();

5. Immediately after the commented line, add the following code:

String language = request.getParameter("language");

6. Save your chages File à Save All


package com.pulpjava.action;

import javax.servlet.http.*;

import org.apache.struts.action.*;

public class TryLingualAction extends Action {

public ActionForward execute(

ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response)

throws Exception {

ActionErrors errors = new ActionErrors();

ActionForward forward = new ActionForward();

try {

//String language =

//request.getLocale().getDisplayLanguage();

String language =

request.getParameter("language");

if (language.equals("French")) {

forward = mapping.findForward("frenchpage");

}

if (language.equals("Spanish")) {

forward = mapping.findForward("spanishpage");

}

if (language.equals("English")) {

forward = mapping.findForward("englishpage"); }

}

catch (Exception e) {

errors.add("name", new ActionError("id"));

}

return (forward); }

}


Testing An HTML Page

1. Open to the Server Perspective Window à Open Perspective à Server

2. From the Servers view, right click on the ‘PulpJava Test Server’ and click ‘Stop.’

If your server is already stopped, the ‘Stop’ option will be grayed out.

It may not be necessary to stop and start the server. However, any time the struts-config.xml file or the web.xml file changes, you will need to bounce your server to ensure the changes take effect.

3. From the ‘Project Navigator’ view of the Servers perspective, open the PulpJavaWeb project, and then open the subfolder named WebContent

4. Right-click on the language.html file and from the context menu, select ‘Run on Server’

5. From the ‘Server Selection’ wizard that appears, make sure the radio button that says ‘Use an existing server’ is select, and the PulpJava Test Server is hightlighted

6. Also check the ‘Set server as project default,’ otherwise this window will keep coming up every time you try to test your application.

7. Click ‘Finish’ and your server will start. Monitor the ‘Console’ view for feedback on the status of the server.

When the server has started, focus will switch to the internal web browser and display your html page.

Enter ‘Engish’ ‘Spanish’ or ‘French into the textfield and click SUBMIT. Remember, it is case sensitive.

Enter in some invalid values as well and see what happens.

The submit button should trigger your TryLingualAction class.




http://www.scja.com/javatutorials/strutsrt.html

Hibernate Tutorials

Sun Certified Java Associate Mock Exams and Tutorials

Testing Applications with IBM Rational Application Developer on WTE WebSphere Test Environment

Testing Your Applications

Once you have created your JSP files, coded your action, and configured your web project to support struts, you are ready to test your application.

To test a JSP or a Servlet, it is usually as simple as right-clicking on the Servlet or JSP in question and selecting 'Run on Server.' With out Struts application, we won't be blessed with as simple a deployment option.

To test your application, perform the following steps:

1. Perform a File à Save All to ensure all editors are saved.

2. Perform a File à Close All to close all open editors.

3. Open the Server Perspective Windows à Open Perspective à Server

4. From the ‘Server Configuration’ window in the lower left corner of the Server perspective, right click and select New à Server and Server Configurations

5. Name the new server ‘PulpJava Test Server’

6. Make sure the Server Type is configured to be a WebSphere 5 Test Environment

7. Click ‘Finish’ to create the server

8. In the ‘Server Configuration’ view, open the Servers folder and notice that the ‘PulpJava Test Server’ has been created.

9. In the Navigator view of the Server perspective, notice that a new folder named ‘Servers’ has been added. This folder contains all of the configuration information for your test server.


Associating an Enterprise Project with a Server

1. From the Server Configuration window in the Servers perspective, open the Servers folder and right-click on the ‘PulpJava Test Server’

2. Click ‘Add and remove projects’ from the context menu.

Your PulpJava project should appear as an available project on the left hand side of the ‘Add or Remove Projects’ wizard.

3. Highlight your PulpJava project on the left hand side and click the Add > button.

After clicking Add >, your PulpJava project should move to the right hand side under ‘Configured Projects’.

4. Click ‘Finish’ to have your PulpJava project associated with your ‘PulpJava Test Server’

In the ‘Server Configuration’ view, the PulpJava enterprise application and the PulpJavaWeb web module should appear as branches under the ‘PulpJava Test Server’ tree.


Starting a Test Server

1. Make sure all editors are saved: File à Save All

2. Make sure all editors are closed: File à Close All

3. From the Servers view, right-click on the ‘PulpJava Test Server’ and select ‘Start’ from the context menu.

4. When the console window reports that ‘server1 open for e-business,’ your test server has successfully started.

NOTE: closing all open editors, especially an editor for the configuring the server, is not a trivial matter. Having an open editor with unsaved changes in may stop a server from starting properly.

Stopping a Test Server

1. From the Servers view, right-click on the ‘PulpJava Test Server’ and select ‘Stop’ from the context menu.

2. The server has terminated when the console reports ‘Server server1 stopped.’


Testing Your Application

Once your test server has been created, your PulpJava project has been associated with your test server, and your test server has been started, testing your application is very simple.

  1. Make sure your test server is started.
  2. Open a web browser such as Internet Explorer or Netscape Navigator
  3. Enter the following url:

http://localhost:9080/PulpJavaWeb/tryLingual.do

4. Your internationalized (English?) message should appear

To test the Spanish message, change the preferred language of your browser. For Internet Explorer:

5.From the IE menu select ToolsàInternet Options

6. In the lower right hand corner of the General tab of the Internet Options page, click ‘Language’

7. In the Language Preference window that appears, take a trip to beautiful Quebec by clicking the Add button and scrolling down until you find "French (Canada) [fr_ca]. Click ‘OK’

8. Move French (Canada) to the top of your preference list using the ‘Move Up’ button and then click ‘OK’

9. Click ‘Apply’ and the ‘OK’ to leave the ‘Internet Options’ window and return to Internet Explorer.

10. Close and then open a new Internet Explorer browser and re-test your application.

Go through the same steps again and take a trip to Argentina by choosing "Spanish (Argentina) [es-ar]" as another preferred language.

Move Spanish up above English and French in the Preferred Languages window and then retest your application. You may need to close Internet Explorer and start it up again to get the change to take effect.

Clearing your cache or doing a CTRL+R to properly refresh your page isn't a bad idea either.

If french is at the top of your preferred language list, you should get the frenchspeaker.jsp page displayed. If you choose Spanish as your preferred language, you should see the spanishspeaker.jsp page displayed. If you choose Swahili as your preferred language, you will run into some problems. I'll leave it up to you to provide your own support for your Swahili users.

Congratulations. You have just created and tested a round trip struts application.






http://www.scja.com/javatutorials/strutsrt.html

Hibernate Tutorials

Sun Certified Java Associate Mock Exams and Tutorials

Creating Action Classes and Action Mappings: Struts Development with WebSphere and Rational Application Developer IRAD

Creating Action Classes and Mappings

1. From the ‘Project Navigator’ view of the Web perspective, right click on the ‘Java Resources’ folder and select New à Other…

The ‘New Resource Wizard’ will appear.

2. On the left pane of the ‘New Resource Wizard’ scroll down and open ‘Web’ Under ‘Web’ you will find an option for Struts resources. Click on ‘Stuts’ to bring up the various Struts resources that can be configured.

3. In the right pane, select ‘Action Class’ and click ‘Next >”

4. Enter the following values:

Java package: com.pulpjava.action

Action class name: TryLingualAction

Ensure that the execute method that takes an HttpServletRequest is selected and click ‘Next >’

We need to create mappings for englishpage, spanishpage and frenchpage.

5.Click the ‘Add’ button adjacent to the listings of Forwards. For name, enter ‘englishpage’ For the mapping, entere ‘./englishspeaker.jsp’

Also map:

frenchpage à ./frenchspeaker.jsp spanishpage à spanishspeaker.jsp

6. Click ‘Finish’ to finally create the TryLingualAction class


Coding the Action

Notice that IBM adds some heavily convoluted code that is supposed to make our Struts development a bit easier. It probably does when you get a little bit more familiar with the Struts framework, but it might make things a little bit confusing at first. Let’s try to deal with it.

At the beginning of the execute method, a Struts ActionErrors object is declared to help with error handling.

Also, and ActionForward is declared to remind the developer that the whole point of the execute method is to eventually figure out where to forward the user.

They even add a try...catch block and tell you to //do something here. That is exactly what we are going to do.

Inside of the try{ } block, lets figure out what language the user is speaking and then send them to the appropriate page.

Anything you want to know about the user can be pulled from the HttpServletRequest object, and if you hunt around in the request object for a little while, you'll find a method called getLocale() that we can use to figure out the preferred language of the user. The languages we are concerned with are English , Spanish and French.

Make the appropriate changes to the execute method of the TryLingualAction.java class so that the code matches the the following:


package com.pulpjava.action;

import javax.servlet.http.*;

import org.apache.struts.action.*;

public class TryLingualAction extends Action {

public ActionForward execute(

ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response)

throws Exception {

ActionErrors errors = new ActionErrors();

ActionForward forward = new ActionForward();

try {

String language =

request.getLocale().getDisplayLanguage();

if (language.equals("French")) {

forward = mapping.findForward("frenchpage");

}

if (language.equals("Spanish")) {

forward = mapping.findForward("spanishpage");

}

if (language.equals("English")) {

forward = mapping.findForward("englishpage");

}

} catch (Exception e) {

errors.add("name", new ActionError("id"));

}

return (forward);

}

}


Once you have coded your TryLingualAction class, you have completed all of the code needed to implement a full request – response cycle using the Struts framework:

  • You have created an enterprise application
  • Your enterprise application contains a web module
  • You added Struts support to your web module
  • You created JSP pages to display output to the user
  • You created an Action class that contains an execute method that determines which page to display to a user
  • A struts-config.xml file was configured with an appropriate action-mapping and local forwards.

The next step is to configure a Servlet/JSP server and test our application.

http://www.scja.com/javatutorials/strutsrt.html

Hibernate Tutorials

Sun Certified Java Associate Mock Exams and Tutorials