Home > Articles

WebObjects Components

Like this article? We recommend

WebObjects Components

A component consists of an HTML file, a Java class file, and something called a WebObjects definition file. The HTML file provides all the static HTML elements for your component along with tags for the dynamic elements. Dynamic elements do not resolve themselves until runtime. In contrast, static HTML elements are exactly the same as when they were created by the developer. You can mix static and dynamic elements in a WebObjects component.

In this part of the chapter, we will start a new project to experiment with building components that contain dynamic elements. So set the Movies project aside for a while; we will get back to it in the next chapter.

Dynamic Elements

Dynamic elements contain certain attributes that are bound to Java variables and methods. When it comes time for these dynamic elements to resolve themselves, they use Java objects to determine how to display their content. A number of Dynamic Elements come with WebObjects; the more commonly used ones are displayed in Table 3.4.

Table 3.4 Common Dynamic Elements

WOString

The most common dynamic element, it represents dynamic text.

WOConditional

Dynamically displays its contents depending on a conditional value.

WORepetition

Repeats its contents dynamically.


There are also dynamic elements for forms, including text fields, lists, pop-up buttons, check boxes, and radio buttons. One of the biggest challenges of learning WebObjects is mastering the usage of all the dynamic elements. These will be covered throughout this book.

Attributes

Dynamic elements contain attributes that govern how the dynamic element will behave, and every dynamic element has a different set of attributes. These attributes are "bound" to values that are relative to the component that contains the dynamic element. These bindings use key-value coding, which is described later, to resolve their values. One of the easiest ways to understand how these bindings work is to go through an example, and a good dynamic element to start with is the WOString.

WOString

The WOString displays dynamic text. The WOString is used to display the contents of one of your variables. It's almost the WebObjects equivalent to printf, only in HTML. The way a WOString works is that when the time comes for it to be displayed, it will display the contents of its value binding.

Using WOString, an Example

The following steps show how to use the WOString by building an application that displays a random number:

  1. Create a new WebObjects application project called RandomNumbers.

  2. Edit the Main.java file in Project Builder. This is the Java file for the Main component. Add a method called randomNumber() that returns a random integer between 0 and 100. The code for Main.java is in Listing 3.1.

  3. Listing 3.1

    The randomNumber() Simply Returns a Random Number between 0–100

    import com.apple.yellow.foundation.*;
    import com.apple.yellow.webobjects.*;
    import com.apple.yellow.eocontrol.*;
    import com.apple.yellow.eoaccess.*;
    
    public class Main
      extends WOComponent
    {
      public int randomNumber()
      {
        return (int)(Math.random()*100.0);
      }
    }
  4. Modify the Main component in WebObjects Builder. Type The random number is in the graphical display.

  5. With the cursor at the end of the sentence you just wrote, add a WOString by clicking the WOString icon.

  6. Now bind randomNumber to the WOString's value attribute. This is done by clicking randomNumber in the lower part of the WebObjects Builder window and dragging it to the center of the WOString as shown in Figure 3.19. If you do not hit the center of the WOString, a pop-up menu will appear with all the WOString attributes, and you can select the value attribute. Save your component.

  7. Figure 3.19 Click the randomNumber value in the Main component and drag it to the WOString to create a binding.

  8. Build and run your application from Project Builder. The result is shown in Figure 3.20.

  9. Figure 3.20 The finished random number application. Click the Refresh button to display a new number.

WOString Bindings

WOString does more than simply display text in an HTML component; the WOString can format your number or date, among other options. Table 3.5 contains a list of WOString bindings. The bindings for a particular dynamic element can be determined by inspecting the element. Figure 3.21 shows the inspector for a WOString. Documentation about the dynamic element can be displayed by clicking the Book icon in the inspector.

Figure 3.21 The Dynamic Inspector shows a list of the available bindings.

Table 3.5 WOString Attributes

Attribute

Description

dateFormat

If the value binding is to a NSGregorianDate object, the dateFormat will determine how the date is displayed. The available formats are documented in the NSGregorianDateFormatter class in the Foundation framework.

escapeHTML

Bound to true (YES) or false (NO), this binding determines how the value will be displayed if it contains HTML control characters. If true, the HTML control characters will be escaped out, meaning that they will be explicitly displayed. If this is false, any HTML tags will be rendered normally.

formatter

If you are displaying data of a custom type, you can also specify a custom formatter. This must be a subclass of NSFormatter, located in the Foundation framework.

numberFormat

Similar to the dateFormat, this specifies how numbers are to be presented. The appropriate values are found in the documentation for the NSNumberFormatter class, located in the Foundation framework.

value

The value to be displayed. Non-string values are converted using the toString method.

valueWhenEmpty

Allows another value to be substituted when the value binding is null. This is useful when the WOString is placed in an HTML table. Instead of an empty table cell, you could set this binding to " ", which is HTML's non-breaking whitespace. This would need to be done in conjunction with the escapeHTML binding being set to NO.


In the WOString inspector, the dateFormat, numberFormat, and escapeHTML bindings all use pop-up lists to assist in setting values. The two format bindings have lists of common formats that allow you to get the formatting done a bit faster. The escapeHTML binding allows you to select YES or NO.

Bindings Behind the Scenes

These bindings that are being discussed are saved with the component. Every component has a directory containing up to three files: The HTML, WOD, and WOO files. The HTML file is the HTML template for the component, and contains place holders for the dynamic elements. The HTML file for the main component in the random numbers example is shown in Listing 3.2.

Listing 3.2

Main.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
  <HEAD>
    <META name="generator" CONTENT="WebObjects 4.5">
    <TITLE>Untitled</TITLE>
  </HEAD>
  <BODY BGCOLOR=#FFFFFF>
    <FONT FACE="Courier, Fixed">The random number is:
    <WEBOBJECT NAME=String1></WEBOBJECT></FONT>
  </BODY>
</HTML>

The HTML file associated with a component consists of mostly legal HTML. Apple has added the WEBOBJECT tag used by WebObjects. The WEBOBJECT tag is found in Listing 3.2. There is always one attribute of this tag, the NAME. This NAME resolves to a name in the associated WOD file, also found in the component directory.

The WOD, or WebObjects definition file determines how the bindings relate to the Java code associated with the component. The WOD file contains a separate entry for every WEBOBJECT tag contained in the HTML file. The first line of the entry contains the name and type of the tag. For example, in Listing 3.2, the NAME specified in the WEBOBJECT tag was String1, which is also the name supplied on the first line of Listing 3.3. The WOD file also specifies that String1 is a WOString. The bindings are specified between the opening and closing braces, each with a key-value pair and ending with a semicolon.

Listing 3.3

Main.wod

String1: WOString {
  value = randomNumber;
}

Binding Resolution

You might have noticed that some bindings are surrounded by double quotes and some are not. For example, in the last tutorial, the value for the WOString was bound to randomNumber. A valid number format would be "###,##0". A value is resolved differently depending on whether it is in double quotes.

If a value is in double quotes, it is evaluated as a literal string. In the number format example, the value is always the string "###,##0".

If a value does not contain double quotes, it is resolved at runtime based on the contents of the Java code that is associated with the component. This resolution is done according to a process called key-value coding. The method valueForKey() is called with the key from the binding being passed in as an argument. The default for a WOComponent is to resolve this according to the key-value coding process, which means that the Java reflection API will be used to introspect the component, looking for certain methods or instance variables.

get Access Method

If the class has a non-private method with the same name as the binding with a prepended get, that method is called. The method must have no parameters and return something other than void. For example, a method with the signature public int getRandomNumber() would be called to resolve the randomNumber binding.

Java developers will recognize this naming convention as the appropriate convention for Java access methods.

Other Access Methods

The next point of search for the appropriate resolution is to look for a method that contains the same signature as the binding. For example, the method containing the signature public int randomNumber() would be used if getRandomNumber() was not found. This is the naming convention used by Objective-C, and is also supported by Java.

CAUTION

The access methods you provide must be non-private. If you provide a private method, the WebObjects framework will determine that it exists and then try to call it, resulting in a runtime error.

Instance Variable

If no method access method exists, the class is searched for a non-private instance variable with the same name as the binding.

TIP

The binding names must begin with a lowercase letter in order for that binding to be resolved properly, as is the convention for method names and instance variables.

A couple of other methods are searched with the same signature as the previous methods—with an underscore at the beginning. The order of the methods searched to resolve a binding is as follows:

  1. get access method; that is, getRandomNumber()

  2. access method; that is, randomNumber()

  3. get private access method; that is, _getRandomNumber()

  4. private access method; that is, _randomNumber()

  5. Instance variable, that is, randomNumber and then _randomNumber.

For more information about key-value coding, take a look at the EOKeyValueCoding interface, located in WOInfoCenter under Reference, Enterprise Objects Framework, EOControl Reference(Java), EOKeyValueCoding.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020