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

No comments: