Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Fixed bad links due to copy-paste from cwiki-test

...

Scrollbar

Let's start building the a basic Hi/-Lo Guessing game.

In the game, the computer selects a number between 1 and 10. You try and guess the number, clicking links. At the end, the computer tells you how many guesses you required to identify the target number. Even a simple example like this will demonstrate several important concepts in Tapestry:

  • Breaking an application into individual pages
  • Transferring information from one page to another
  • Responding to user interactions
  • Storing client information in the server-side session

We'll build it this little application in small pieces, using the kind of iterative development that Tapestry makes so easy.

...

Our page flow is very simple, consisting of three pages: Index (the starting page), Guess and GameOver. The Index page introduces the application and includes a link to start guessing. The Guess page presents the user with ten links, plus feedback such as "too low" or "too high". The GameOver page tells the user how many guesses they took before finding the target number.

Index Page

Let's get to work on the Index page and template.. Make Index.tml look like this:

Code Block
Code Block
languagexml
langxml
titleIndex.tml

<html t:type="layout" title="Hi/Lo Guess"
    xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_03.xsd">

    <p>
        I'm thinking of a number between one and ten ...
    </p>

    <p>
        <a href="#">start guessing</a>
    </p>

</html>

Running the application gives us our start:

Image Removed

And edit the corresponding Java class, Index.java, removing its body (but you can leave the imports in place for now):

Code Block
languagejava
langjava
titleIndex.java
package com.example.tutorial1.pages;

public class Index
{
}

Running the application gives us our start:

Image Added

However, clicking the link doesnHowever, clicking the link doesn't do anything yet. , as its just a placeholder <a> tag, not an actual Tapestry component. Let's fix that. First: think about what should happen when the link is clicked?user clicks that link:

  • A random target number between 1 and 10 should be selected
  • The number of guesses taken should be reset to 0
  • The user should be sent to the Guess page to make a guess

Our first step is to find out when the user clicks that "start guessing" link. In a typical web application framework, we might start thinking about URLs and handlers and maybe some sort of XML configuration file. But this is Tapestry, so we're going to work with components and methods on our classes.

First, the component. We want to perform an action (selecting the number) before continuing on to the Guess page. The ActionLink component is just what we need; it creates a link with a URL that will trigger an action event in our code ... but that's getting ahead of ourselves. First up, convert the \<a\> <a> tag to an ActionLink component:

Code Block
languagexml
langxml
titleIndex.tml (partial)

    <p>
        <t:actionlink t:id="start">start guessing</t:actionlink>
    </p>

If you refresh the browser and hover your mouse over the "start guessing" link, you'll see that the URL for the "start guessing" link its URL is now /tutorial1/index.start}, which identifies the name of the page ("index") and the id of the component ("start").

If you click the link now, you'll get an error:

Image RemovedImage Added

Tapestry is telling us that we need to provide some kind of event handler for that event. What does that look like?

An event handler is a method of the Java class with a special name. The name is onevent-nameEventnameFromcomponentComponent-id ... here we want a method named onActionFromStart(). How do we know that "action" is the right event name? Because that's what ActionLink does, that's why its named _Action_Link.

...

Once again, Tapestry gives us options; if you don't like naming conventions, there's an

...

@OnEvent annotation you can place on the method instead, which restores the freedom to name the method as you like. Details about this approach are in the Tapestry Users' Guide. We'll be sticking with the naming convention approach for the tutorial.

When handling a component event request (the kind of request triggered by the ActionLink component's URL), Tapestry will find the component and trigger a component event on it. This is the callback our server-side code needs to figure out what the user is doing on the client side. Let's start with an empty event handler:

Code Block
languagejava
langjava
titleIndex.java

package com.example.tutorialtutorial1.pages;

public class Index
{
    void onActionFromStart()
    {

    }
}

In the browser, we can re-try the failed component event request by hitting the refresh button ... or we can restart the application. In either case, we get the default behavior, which is simply to re-render the page.

...

Note that the event handler method does not have to be public; it can be protected, private, or package private (as in this example). By convention, such methods are package private, if for no other reason than

...

it is the minimal amount of characters to type.

HmHmm... Right right now you have to trust me us that the method got invoked. That's no good ... what's a quick way to tell for sure? One way would be have the method throw an exception, but that's a bit ugly.

How about this: add the @Log @Log annotation to the method:

Code Block
languagejava
langjava
titleIndex.java (partial)
import org.apache.tapestry5.annotations.Log;

. . .

    @Log
    void onActionFromStart()
    {

    }

When you next click the link you should see the following in the Eclipse console:

No Format

[DEBUG] pages.Index [ENTER] onActionFromStart()
[DEBUG] pages.Index [ EXIT] onActionFromStart
[INFO] AppModule.TimingFilter Request time: 3 ms
[INFO] AppModule.TimingFilter Request time: 5 ms

The @Log annotation directs Tapestry to log method entry and exit. You'll get to see any parameters passed into the method, and any return value from the method ... as well as any exception thrown from within the method. It's a powerful debugging tool. This is an example of Tapestry's meta-programming power, something we'll use quite a bit of in the tutorial.

...

Why

...

do we see two requests for one click? Tapestry uses an approach based on the Post/Redirect

...

/Get pattern. In fact, Tapestry generally performs a redirect after each component event. So the first request was to process the action, and the second request was to re-render the Index page. You can see this in the browser, because the URL is still "/tutorial1" (the URL for rendering the Index page). We'll return to this in a bit.

We're ready for the next step, which involves tying together the Index and Guess pages. Index will select a target number for the user to Guess, then "pass the baton" to the Guess page.

Let's start by thinking about the Guess page. It needs a variable to store the target value in, and it needs a method that the Index page can invoke, to setup set up that target value.

Code Block
languagejava
titleGuess.java

package com.example.tutorialtutorial1.pages;

public class Guess
{
    private int target;

    void setup(int target)
    {
        this.target = target;
    }
}

With Create that in mindGuess.java file in the same folder as Index.java. Next, we can modify Index to invoke this new the setup() method of our new Guess page class:

Code Block
languagejava
langjava
titleIndex.java (revised)

package com.example.tutorialtutorial1.pages;

import java.util.Random;

import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Log;

public class Index
{
    private final Random random = new Random(System.nanoTime());

    @InjectPage
    private Guess guess;

    @Log
    Object onActionFromStart()
    {
        int target = random.nextInt(10) + 1;

        guess.setup(target);

        return guess;
    }
}

The new event handler method now chooses the target number, and tells the Guess page about it. Because Tapestry is a managed environment, we don't just create an instance of Guess ... it is Tapestry's responsibility to manage the lifecycle life cycle of the Guess page. Instead, we ask Tapestry for the Guess page, using the @InjectPage annotation.

Note

All fields in a Tapestry page or component class must be private non-public.

Once we have that Guess page instance, we can invoke methods on it normally.

...

So ... let's click the link and see what we get:

Image RemovedImage Added

Ah! We didn't create a Guess page template. Tapestry was really expecting us to create one, so we better do so. Remember to create it as

Code Block
languagejava
langxml
titlesrc/main/resources/com/

...

example/tutorial/pages/Guess.tml

...

Code Block
langxml
titleGuess.tml

<html t:type="layout" title="Guess The Number"
    xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_03.xsd">

    <p>
        The secret number is: ${target}.
    </p>
  
</html>

Hit the browser's back button, then click the "start guessing" link again. We're getting closer:

Image RemovedImage Added

If you scroll down, you'll see the line of the Guess.tml template that has the error. We have a field named target, but it is private and there's no corresponding property, so Tapestry was unable to access it.

We just need to write the missing JavaBeans accessor methods getTarget() (and setTarget() for good measure). Or we could let Tapestry do it inteadwrite those methods instead:

Code Block
languagejava
langjava

    @Property
    private int target;

The @Property @Property annotation very simply directs Tapestry to write the getter and setter method for you. You only need to do this if you are going to reference the field from the template.

We are getting very close but there's one last big oddity to handle. Once you refresh the page you'll see that target is 0!

Image RemovedImage Added

What gives? We know it was set to at least 1 ... where did the value go?

Welcome to Tapestry state management. By default, at the end of each request, Tapestry wipes out the As noted above, Tapestry sends a redirect to the client after handling the event request. That means that the rendering of the page happens in an entirely new request. Meanwhile, at the end of each request, Tapestry wipes out the value in each instance variable. So that means that target was a non-zero number during the component event request ... but by the time a the new page render request comes up from the web browser to render the Guess page, its value is the value of the target field has reverted back to its default, zero.

The solution here is to mark which fields have values that should persist from one request to the next (and next, and next ...). Thats That's what the @Persist @Persist annotation is for:

Code Block
languagejava
langjava

    @Property  
    @Persist
    private int target;

This doesn't have anything to do with database persistence (that's coming up in a later chapter). It means that the value is stored in the HttpSession between requests.

Go back to the Index page and click the link again. Finally, we have a target number:

Image RemovedImage Added

That's enough for us to get started. Let's build out the Guess page, and get ready to let the user make guesses. We'll show the count of guesses, and increment that count when they make them. We'll worry about high and low and actually selecting the correct value later.

You can go either way here; let's When building Tapestry pages, you sometimes start with the Java code and build the template to match, and sometime start with the template and build the Java code to match. Both approaches are valid. Here, lets start with the markup in the template, then figure out what we need int in the Java code to make it work.

Code Block
languagexml
langxml
titleGuess.tml (revised)

<html t:type="layout" title="Guess The Number"
    xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_03.xsd"
    xmlns:p="tapestry:parameter">

  <p:sidebar>
    <p>
        The secret number is: ${target}.
    </p>
 
  </p:sidebar>

  <strong>Guess number #$${guessCount}</strong>
 
  <p>Make  <p>Make a guess from the options below:</p>
 
  <ul>  <ul class="list-inline">
        <t:loop source="1..10" value="current">
            <li>
            <t:actionlink t:id="makeGuess" context="current">${current}
            </t:actionlink>
            </li>
        </t:loop>
    </ul>
 
</html>

So it looks like we need a guessCount property that starts at 1.

...

So, the Loop component is going to set the current property to 1, and render its body (the \<li\> tag, and the ActionLink component). Then its going to set the current property to 2 and render its body again ... all the way up to 10.

Warning

It's not enough to just say that the Loop component will update property current ... we have to actually add the current property to the Java class. The information in the template configures the Loop component for use in the Guess page, but doesn't change the structure of the Guess page ... that's done in the Java code.

And notice what we're going with the ActionLink component; its no longer enough to know the user clicked on the ActionLink ... we And notice what we're doing with the ActionLink component; its no longer enough to know the user clicked on the ActionLink ... we need to know which iteration the user clicked on. The context parameter allows a value to be added to the ActionLink's URL, and we can get it back in the event handler method.

Info

The URL for the ActionLink will be /tutorial1/guess.makeguess/3. That's the page name, "Guess", the component id, "makeGuess", and the context value, "3".

Code Block
languagejava
langjava
titleGuess.java (revised)

package com.example.tutorialtutorial1.pages;

import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;

public class Guess
{
    @Property
    @Persist
    private int target, guessCount;

    @Property
    private int current;

    void setup(int target)
    {
        this.target = target;
        guessCount = 1;
    }

    void onActionFromMakeGuess(int value)
    {
        guessCount++;
    }

}

The revised version of Guess includes two new properties: current and guessCount. There's also a handler for the action event from the makeGuess ActionLink component; currently it just increments the count.

Notice that the onActionFromMakeGuess() method now has a parameter: the context value that was encoded into the URL by the ActionLink. When then user clicks the link, Tapestry will automatically extracts extract the string and converts from the URL, convert it to an int and passes pass that int value to into the event handler method. More boilerplate code you don't have to write.

At this point, the page is partially operational:

Image Removed

On the Java side, the Guess page needs to have a target property:

Image Added

Our next step is to actually check the value provided by the user against the target and provide feedback: either they guessed too high, or too low, or just right. If they get it just right, we'll switch to the GameOver page with a message such as "You guessed the number 5 in 2 guesses".

Let's start with the Guess page; it now needs a new property to store the message to be displayed to the user, and needs a field for the injected GameOver page:

Code Block
languagejava
langjava
titleGuess.java (partial)
    @Property
    @Persist(PersistenceConstants.FLASH)
    private String message
No Format

package org.apache.tapestry5.tutorial.pages;

public class Guess
{
  private int target;

  Object initialize(int target)
  {
    this.target = target;

    return this;
  }
}

The key method here is initialize(): It is invoked to tell the Guess page what the target number is. Notice that the method is package private, not public; it is only expected to be invoked from the Index page (as we'll see in a moment), so there's no need to make it public. Later we'll see that there's more initialization to be done than just storing a value into the target instance variable (which is why we don't simply name the method setTarget() ).

Now we can move back to the Index page. What we want is to have the ActionLink component invoke a method on the Index page. We can then generate a random target number. We'll tell the Guess page what the target number is and then make sure that it is the Guess page, and not the Index page, that renders the response into the user's web browser. That's actually quite a few concepts to take in all at once.

Let's start with the code, and break it down:

src/main/java/org/apache/tapestry5/tutorial/pages/Index.java

No Format

package org.apache.tapestry5.tutorial.pages;

import java.util.Random;

import org.apache.tapestry5.annotations.InjectPage;

public class Start
{
  private final Random random = new Random();

  @InjectPage
  private Guess guess;

  Object onAction()
  {
    int target = random.nextInt(10) + 1;

    return guess.initialize(target);
  }
}

What we're talking about here is communication of information from the Index page to the Guess page. In traditional servlet development, this is done in a bizarre way ... storing attributes into the shared HttpSession object. Of course, for that to work, both (or all) parties have to agree on the type of object stored, and the well-known name used to access the attribute. That's the source of a large number of bugs. It's also not very object oriented ... state is something that should be inside objects (and private), not outside objects (and public).

The Tapestry way is very object oriented: everything is done in terms of objects and methods and properties of those objects.

This communication starts with the connection between the two pages: in this case, the InjectPage|||\ annotation allows another page in the application to be injected into the Index page.

Injection can be a somewhat nebulous concept. In terms of Tapestry, it means that some cooperating object needed by one class is provided to it. The other object is often referred to as a "dependency"; in this case, the Index page depends on the Guess page to be fully functional, and an instance of the Guess page is made available as the guess instance variable. The Index page doesn't, and can't, create the Guess page, it can only advertise, to Tapestry, that it needs the Guess page. Tapestry will take care of the rest.

Let's see what we do with this injected page. It's used inside onAction(). You might guess that this method is invoked when the link ("Start guessing") is clicked. But why?

This is a strong example of convention over configuration. Tapestry has a naming convention for certain methods: "onEventTypeFromComponentId". Here, the event type is "action" and the component id is not even specified. This translates to "when the action event is fired from any component, invoke this method".

"The action event?" This underlines a bit about how Tapestry processes requests. When you click a link generated by the ActionLink component, Tapestry is able to identify the underlying component inside the request: it knows that the component is on the Index page, and it knows the component within the page. Here we didn't give the ActionLink component a specific id, so Tapestry supplied one. An "action" event is triggered inside the ActionLink component, and that event bubbles up to the page, where the onAction() method acts as an event handler method.

So ... ActionLink component -> action request -> onAction() event handler method.

Event handler methods don't have to be public; they are usually package private (as in this example). Also, it isn't an error if a request never matches an event handler. Before we added the onAction() event handler, that's exactly what happened; the request passed through without any event handler match, and Tapestry simply re-rendered the Start page.

What can you do inside an event handler method? Any kind of business logic you like; Tapestry doesn't care. Here we're using a random number generator to set the target number to guess.

We also use the injected Guess page; we invoke the initialize() method to tell it about the number the user is trying to guess.

The return value of an event handler method is very important; the value returned informs Tapestry about what page will render the response to the client. By returning the injected Guess page, we're telling Tapestry that the Guess page should be the one to render the response.

This idiom: having the Guess page provide an initialize() method and return itself, is very common in Tapestry. It allows the event handler method to be very succinct; it's as if the event handler method says "initialize the Guess page and render it to the client".

Again, this is a big difference between Tapestry and servlets (or Struts). Tapestry tightly binds the controller (the Java class) to the template. Using JSPs, you would have extra configuration to select a view (usually by a logical name, such as "success") to a "view" (a JSP). Tapestry cuts through all that cruft for you. Objects communicate with, and defer to, other objects and all the templates and rendering machinery comes along for free.

In later chapters, we'll see other possibilities besides returning a page instance from an event handler method.

For the moment, make sure all the changes are saved, and click the "Start guessing" link.

Image Removed

Exception on the Guess page

This may not quite be what you were expecting ... but it is a useful digression into one of Tapestry's most important features: feedback.

Something was wrong with the Guess page, and Tapestry has reported the error to you so that you can make a correction.

Here, the root problem was that we didn't define a getTarget() method in the Guess class. Ooops. Deep inside Tapestry, a RuntmeException was thrown to explain this.

As often happens in frameworks, that RuntimeException was caught and rethrown wrapped inside a new exception, the TapestryException. This added a bit more detail to the exception message, and linked the exception to a location. Since the error occurred inside a component template, Tapestry is able to display that portion of the template, highlighting the line in error.

If you scroll down, you'll see that after the stack trace, Tapestry provides a wealth of information about the current request, including headers and query parameters. It also displays information stored in the HttpSession (if the session exists), and other information that may be of use.

Of course, in a production application, this information can be hidden!

Let's fix this problem, by adding the following to the Guess class:

No Format

  public int getTarget()
  {
    return target;
  }

Persisting data between requests

That fixes the problem, but introduces another:

Image Removed

Hi/Lo Guess Page

Why is the target number zero? Didn't we set it to a random value between 1 and 10?

At issue here is the how Tapestry organizes requests. Tapestry has two main types of requests: action requests and render requests. Render requests are easy, the URL includes just the page name, and that page is rendered out.

Action requests are more complicated; the URL will include the name of the page and the id of the component within the page, and perhaps the type of event.

After your event handler method is executed, Tapestry determine what page will render the response; as we've seen, that is based on the return value of the event handler method.

Tapestry doesn't, however, render the response directly, the way most servlet applications would; instead it sends a redirect URL to the client web browser. The URL is a render request URL for the page that will render the response.

You may have seen this before. It is commonly called the redirect after post pattern. Most often, it is associated with form submissions (and as we'll see in later chapters, a form submission is another type of action request).

So why does that affect the target value? At the end of any request (action or render), Tapestry will "clean house", resetting any instance variables back to their initial, default values (usually, null or zero).

This cleaning is very necessary to the basic way Tapestry operates: pages are expensive entities to create; too expensive to create fresh each request, and too large and complicated to store in the HttpSession. Tapestry pools pages, using and reusing them in request after request.

For the duration of a single request from a single user, a page instance is bound to the request. It is only accessible to the one request. Other requests may be bound to other instances of the same page. The same page instance will be used for request after request.

So, inside the action request, the code inside the onAction() event handler method did call the initialize() method, and a value between 1 and 10 was stored in the target instance variable. But at the end of that request, the value was lost, and in the subsequent render request for the Guess page, the value was zero.

Fortunately, it is very easy to transcend this behavior. We'll use an annotation, Persist, on the instance variable:

No Format

  @Persist
  private int target;

Now we can use the browser back button to return to the Start page, and click the link again.

Image Removed

The target number

One of the nice things about this approach, the use of redirects, is that hitting the refresh button does not choose a new target number. It simply redraws the Guess page with the target number previously selected. In many servlet applications, the URL would be for the action "choose a random number" and refreshing would re-execute that action.

Now it's time to start the game in earnest. We don't want to just tell the user what the target number is, we want to make them guess, and we want to track how many attempts they take.

What we want is to create 10 links, and combine those links with logic on the server side, an event handler method, that can interpret what value the user selected.

Let's start with those links. We're going to use a new component, Loop, to loop over a set of values:

src/main/webapp/Guess.tml:

No Format

<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_0.xsd">
  <head>
    <title>Guess A Number</title>
  </head>
  <body>

  <p>Make a guess between one and ten:</p>

    <t:loop source="1..10" value="guess" xml:space="preserve">
      <t:actionlink t:id="link" context="guess">${guess}</t:actionlink>
    </t:loop>

  </body>
</html>

The Loop component's source attribute identifies the values to loop over. Often this is a list or array, but here the special special syntax, "1..10" means iterate over the numbers between 1 and 10, inclusive.

What about the xml:space="preserve" attribute? Normally, Tapestry is pretty draconian about stripping out unnecessary whitespace from the template. Most whitespace (spaces, tabs, newlines, etc.) is reduced to a single space. This can help a lot with reducing the size of the output and with making complex nested layouts easier to read ... but occasionally, as here, the whitespace is needed to keep the numbers from running together. xml:space="preserve" turns on full whitespace retention for the element.

The value attribute gets assigned the current item from the loop. We'll use a property of the Guess page as a kind of scratchpad for this purpose. We could manually write a getter and a setter method as we did before, or we can let Tapestry generate those accessors:

No Format

  @Property
  private int guess;

Tapestry will automatically create the methods needed so that the guess property (it's smart about stripping off leading underscores) is accessible in the template.

The context parameter of the ActionLink is how we get extra information into the action request URL. The context can be a single value, or an array or list of values. The values are converted to strings and tacked onto the action request URL. The end result is http://localhost:8080/tutorial1/guess.link/4.

What is "guess.link"? That's the name of the page, "guess", and the id of the component ("link", as explicitly set with the t:id attribute). Remember this is an action link: as soon as the user clicks the click, it is replaced with a render link such as http://localhost:8080/tutorial1/guess.

Now, to handle those guesses. We're going to add an event handler method that gets invoked when a link is clicked. We're also going to add a new property, message, to store the message that says "too high" or "too low".

No Format

  @Persist
  @Property
  private String message;

  String onActionFromLink(int guess)
  {
    if (guess == target) return "GameOver";

    if (guess < target)
      message = String.format("%d is too low.", guess);
    else
      message = String.format("%d is too high.", guess);

    return null;
  }

Here's the big news: Tapestry will convert the number from the URL back into an integer automatically, so that it can pass it in to the onActionFromLink() event handler method as a method parameter. We can then compare the guess from the user to the secret target number.

Notice how Tapestry adapts to the return value. Here it may be null ... Tapestry interprets that as "stay on the same page". You may also return a string ("GameOver"); Tapestry interprets that as the name of the page to render the response.

We need to update the Guess page to actually display the message; this is done by adding the following:

No Format

  <p>${message}</p>

This is truly bare bones and, when message is null, will output an empty <p> element. A real application would dress this up a bit more (using CSS and the like to make it prettier).

We do need a basic GameOver page.

src/main/webapp/GameOver.tml:

No Format

<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_0.xsd">
  <head>
    <title>Game Over!</title>
  </head>
  <body>

    <h1>Game Over</h1>

    <p> You guessed the secret number!  </p>


  </body>
</html>

src/main/java/org/apache/tapestry5/tutorial/pages/GameOver.java:

No Format

package org.apache.tapestry5.tutorial.pages;

public class GameOver
{

}

With this in place, we can make guesses, and get feedback from the application:

Image Removed

Feedback from the game

Counting the number of guesses

It would be nice to provide some feedback about how many guesses the user took to find the number. That's easy enough to do.

First we update Guess to store the number of guesses:

No Format

  @Persist
  @Property
  private int count;

Next we modified initialize() to ensure that count is set to 0. This is a safety precaution in case we add logic to play the game again.

No Format

  Object initialize(int target)
  {
    this.target = target;
    this.count = 0;

    return this;
  }

We have a couple of changes to make to the event handler method. We want to communicate to the GameOver page the guess count; so we'll inject the GameOver page so we can initialize it.

No Format

  Object onActionFromLink(int guess)
  {
    count++;

    if (guess == target) return gameOver.initialize(count);

    if (guess < target)
      message = String.format("%d is too low.", guess);
    else
      message = String.format("%d is too high.", guess);

    return null;
  }

So, we update the count before comparing and, instead of returning the name of the GameOver page, we return the configured instance.

Lastly, we need to make some changes to the GameOver class.

src/main/java/org/apache/tapestry5/tutorial/GameOver.java:

@InjectPage
    private GameOver gameOver;

First off, we're seeing a variation of the @Persist annotation, where a persistence strategy is provided by name. FLASH is a built-in strategy that stores the value in the session, but only for one request ... it's designed specifically for these kind of feedback messages. If you hit F5 in the browser, to refresh, the page will render but the message will disappear.

Next, we need some more logic in the onActionFromMakeGuess() event handler method:

Code Block
languagejava
langjava
titleGuess.java (partial)
    Object onActionFromMakeGuess(int value)
    {
        if (value == target)
        {
            gameOver.setup(target, guessCount);
            return gameOver;
        }

        guessCount++;

        message = String.format("Your guess of %d is too %s.", value,
            value < target ? "low" : "high");

        return null;
    }

Again, very straight-forward. If the value is correct, then we configure the GameOver page and return it, causing a redirect to that page. Otherwise, we increment the number of guesses, and format the message to display to the user.

In the template, we just need to add some markup to display the message:

Code Block
languagexml
langxml
titleGuess.tml (partial)
    <strong>Guess number ${guessCount}</strong>

    <t:if test="message">
        <p>
            <strong>${message}</strong>
        </p>
    </t:if>

This snippet uses Tapestry's If component. The If component evaluates its test parameter and, if the value evaluates to true, renders its body. The property bound to test doesn't have to be a boolean; Tapestry treats null as false, it treats zero as false and non-zero as true, it treats an empty Collection as false ... and for Strings (such as message) it treats a blank string (one that is null, or consists only of white space) as false, and a non-blank string is true.

We can wrap up with the "GameOver" page:

Code Block
languagejava
titleGameOver.java
package com.example.tutorial1.
No Format

package org.apache.tapestry5.tutorial.pages;

import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;

public class GameOver
{
    @Property
    @Persist
  @Property
  private int target, countguessCount;
	
    Objectvoid initializesetup(int counttarget, int guessCount)
    {
        this.counttarget = counttarget;

       return this.guessCount = guessCount;
    }
}

...


Code Block
languagexml
titleGameOver.tml

...

<html t:type="layout" title="Game Over"
   

...

No Format

<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_03.xsd"
    xmlns:p="tapestry:parameter">

  <head>
  <p>
        <title>Game Over!</title>
  </head>
  <body>

You guessed the number
       <h1>Game Over</h1>
<strong>${target}</strong>
    <p> You guessed the secretin
 number in ${count} guesses!  </p>


  <strong>${guessCount}</body>
</html>

Parting thoughts

What we've gone after here is the Tapestry way: pages as classes that store internal state and communicate with each other. We've also seen the Tapestry development pattern: lots of simple small steps that leverage Tapestry's ability to reload templates and classes on the fly.

We've also seen how Tapestry stores data for us, sometimes in the session (via the @Persist annotation) and sometimes in the URL.

Our code is wonderfully free of anything related to HTTP or the Java Servlet API. We're coding using real objects, with their own instance variables and internal state.

Our application is still pretty simple; here's a few challenges:

  • Add a restart link to the GameOver page to allow a new game to start. Can you refactor the application so that the code for the random number selection occurs in only one place?
  • As we guess, we're identifying ranges of valid and invalid numbers. Can you only show valid guesses to the user?
  • What would it take to change the the game to choose a number between 1 and 20? Between 1 and 100?
  • What about setting an upper-limit on the number of guesses allowed?
strong>
        guesses.
    </p>
  
</html>

The result, when you guess correctly, should be this:

Image Added

That wraps up the basics of Tapestry; we've demonstrated the basics of linking pages together and passing information from page to page in code as well as incorporating data inside URLs.

There's still more room to refactor this toy application; for example, making it possible to start a new game from the GameOver page (and doing it in a way that doesn't duplicate code). In addition, later we'll see other ways of sharing information between pages that are less cumbersome than the setup-and-persist approach shown here.

Next up: let's find out how Tapestry handles HTML forms and user input.

Next: Using BeanEditForm To Create User Forms

Scrollbar

 

 Continue on to Chapter 4: Tapestry and Forms