Passing Data to the View Using Attributes: Constants.java


Passing Data to the View Using Attributes: Constants.java

In the earlier section on the Action class ( HelloAction.java ), you saw how the Action class passed between itself and the View components using the setAttribute() and getAttribute() methods of the request object. Now let's look at this process in a bit more detail.

When you pass an object from the ActionClass to the View component (a JSP page) using the request.setAttribute() , you need to provide a name , or string identifier, that the JSP file can use to retrieve the object with. In Struts applications, a convention has been adopted for using a file named Constants.java to define these names . Listing 3.6 contains the Constants.java file for the HelloWorld! application.

Listing 3.6 The Hello World! Application Constants file ( Constants.java )
 package ch03.hello; /**  * Constants to be used in the Hello World! Example  * Chapter 03 of "Struts: Rapid Working Knowledge"  *  * @author Kevin Bedell  */ public final class Constants {    /**      * The application scope attribute under which our user database      * is stored.      */     public static final String HELLO_KEY = "ch03.hello"; } 

For the HelloWorld! application, there is only a single bean passed between an Action class and a View component (JSP file).

Notice that the class and all String s defined in it are defined as public static final String fields in the class. This is because they are used as constants and need never change.

The alternative to defining these values as constants is to enter them as text values in each file in which they are used (for example, in both HelloAction.java and hello.jsp ). Typing in String s as constants directly in files leads to errors when, inevitably, someone changes the value in one place and not the other. Then suddenly it looks to the JSP developer as if the bean has just disappeared!

Also, although the HelloWorld! example shows a bean being passed as an attribute on the request, there are times when it's better to pass the object by attaching it as an attribute to the session object using session.setAttribute() . Choosing either request or session scope for the form bean is fine; it just depends on the needs of your application.



Struts Kick Start
Struts Kick Start
ISBN: 0672324725
EAN: 2147483647
Year: 2002
Pages: 177

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net