dcsimg
December 10, 2016
Hot Topics:

Wicket: The First Steps

  • April 23, 2007
  • By Karthik Gurumurthy
  • Send Email »
  • More Articles »

Adding a Link to the Welcome Page

Add a link named "Login" that is intended to take you back to the Login page, as shown in Listing 20. (Normally, there is no reason why somebody would want to do this, but this will let you quickly cover some ground with Wicket development.)

Listing 20. Welcome.html

<html>
  <title>Welcome to Wicket Application</title>
  <body>
    Welcome To Wicket Mr <span wicket:id="message">Message goes here</span>
    <a href="#" wicket:id='linkToUserProfile'>User Profile</a><br/>
    <a href="#" wicket:id='linkToLogin'>Login</a><br/></body>
</html>

Now you will see how a click on an HTML link translates to an onClick event on the corresponding server-side component.

Modify the Page class in order to accommodate the links and set the target page in the onClick method of wicket's Link class (see Listing 21).

Listing 21. Welcome.java

import wicket.markup.html.link.Link;

  class Welcome ..

    public Welcome(){
      //..
      //..
      Link linkToUserProfile = new Link("linkToUserProfile"){
         public void onClick(){
          // Set the response page
          setResponsePage(UserProfilePage.class);
        }
      };

      Link linkToLogin = new Link("linkToLogin"){
         public void onClick(){
           setResponsePage(Login.class);
         }
      };

      // Don't forget to add them to the Form
      form.add(linkToUserProfile);
      form.add(linkToLogin);
   }
}
Page Instance Caching

After the page is rendered, it is put into a PageMap. The PageMap instance lives in session and keeps the last n pages ( this number is configurable through Wicket's ApplicationSettings object). When a form is submitted, the page is brought back from PageMap and the form handler is executed on it. The PageMap uses a Least Recently Used (LRU) algorithm by default to evict pages-to reduce space taken up in session. You can configure Wicket with your own implementation of the eviction strategy. Wicket specifies the strategy through the interface wicket.session.pagemap.IPageMapEvictionStrategy. You can configure your implementation by invoking getSessionSettings().setPageMapEvictionStrategy (yourPageMapEvicationStrategyInstance) in the WebApplication.init() method. This could prove to be extremely crucial when tuning Wicket to suit your application needs.

Go back to the login page, enter values for user ID and password, and click the Login button. You should see something like what appears in Figure 6.

Figure 6. Welcome page with links to other pages

The rendered URL for the "Login" link looks like this:

<a href="/wicket/helloworld?wicket:interface=:0:form:linkToLogin::
ILinkListener" wicket:id="linkToLogin">Login</a><br/>

This URL has a reference to a particular page instance in the PageMap (denoted by parameter:0) at this point in time and hence is not bookmarkable. You will see later how you can have bookmarkable links that can be cached in the browser for use at a later point in time.

Click the "Login" link and you should be taken to the login screen again (see Figure 7).

Figure 7. Clicking the "Login" link displays the login page with blank fields.

The User Name and Password fields turn out to be blank. This was because you specified the response page class-Login.class-on onClick. Wicket accordingly created a new instance of the Login page and rendered that on the browser. Since the Login constructor initializes the TextField and PasswordTextField widgets to empty strings, the corresponding HTML widgets turn out blank on the browser. Note that you could have passed the original Login page instance to the Welcome page and specified that as the argument to setResponsePage on onClick. That way you would have gotten back the "original" Login page with the user input intact. This scenario is indicated in Listing 22.

Listing 22. Welcome Page Modified to Accept the Previous Page During Construction

public class Welcome extends WebPage {
    String userId;
    Page prevPage;

    public Welcome(String userId, Page prevPage){
      this.userId;
      this.prevPage = prevPage;
      //..
    }

    Link linkToLogin = new Link("linkToLogin"){
       public void onClick(){
         setResponsePage(prevPage==null?new Login():prevPage);
       }
    };
}

Listing 23 shows the modifications needed to the Login page.

Listing 23. Login Page Modified to Pass Itself As the Argument

public class Login extends WebPage {
  //..
  class LoginForm extends Form {
    public LoginForm(String id) {
      super(id);
    }

    @Override
    public void onSubmit() {
      String userId = getUserId();
      String password = getPassword();
      /* Instantiate the result page and set it as the response page */
      Welcome welcomePage = new Welcome(userId,Login.this);
      setResponsePage(welcomePage);
    }
  }

}

Now click the "Login" link, and it should take you back to the login page with the previously entered input intact.

This tells us that Wicket is an unmanaged framework. You can instantiate pages or components anywhere in the application, and the framework doesn't restrict you in any fashion. It is in fact a widely followed practice when developing applications with Wicket. In this respect, it's quite different from managed frameworks, like Tapestry, which don't allow you to instantiate pages at any arbitrary point in your code.

In this example, you set out to develop a login use case, and not having an authentication feature, however trivial it may be, just doesn't cut it. Let's quickly put one in place.

Adding Basic Authentication to the Login Page

Let's add a basic authentication mechanism to the login page (see Listing 24). For now, you will support "wicket"/"wicket" as the only valid user ID/password combination.

Listing 24. Login.java

public class Login extends WebPage
   //..
  public Login() {

    Form form = new LoginForm("loginForm");
     //...
  }

  class LoginForm extends Form {
    public LoginForm(String id) {
      super(id);
  }

  @Override
  public void onSubmit() {
      String password = getPassword();
      String userId = getUserId();
      if (authenticate(userId,password)){
         Welcome welcomePage = new Welcome();
         welcomePage.setUserId(userId);
         setResponsePage(welcomePage);
      }else{
         System.out.println("The user id/ password
              combination is incorrect!n");
      }
    }
  }
  public final boolean authenticate(final String username,
           final String password){
       if ("wicket".equalsIgnoreCase(username) &&
          "wicket".equalsIgnoreCase(password))
         return true;
        else
         return false;
   }
}

If you supply an invalid user ID/password combination, you will not see the Welcome page in response. Since you didn't specify a response page for this scenario, Wicket will redisplay the current page, i.e., the login page instead (via postback mechanism). One glaring issue with this example is that the user doesn't really get to know what actually went wrong, as the failed login information is logged to the console.

Summary

In this article, you learned how to set up Wicket, Eclipse, and the Jetty Launcher Plug-in for Wicket-based web development. You also learned that Wicket Form and TextField components help in user interaction. Every HTML widget has an equivalent Wicket component. These components, in turn, rely on the model object to get and set data during template rendering and submission. You learned to use two of Wicket's IModel implementations-PropertyModel and CompoundPropertyModel. You also saw that there are various ways of configuring the model objects and briefly explored the "Tapestry way" and "Struts/JSF way" of writing model objects. The Form component's onSubmit() method should be overridden to process user inputs. Wicket caches pages in a PageMap for a given session and follows the LRU algorithm to evict pages from the cache. Wicket allows you to configure a custom implementation of the page-eviction strategy as well. Later, you learned that the Component.setResponsePage method can be used to direct the user to a different page after page submit. You also used Wicket's Link component, which maps to an HTML link, to direct users to a different page. Through the Welcome page that has links, you also learned that Wicket is an unmanaged framework that allows you to instantiate pages or components anywhere in the application, and this framework doesn't restrict you in any fashion.

About the Author

Karthik Gurumurthy has been associated with the IT industry for more than six years now and has employed open source libraries to solve business problems. Karthik also has the experience of having documented a popular open source project: XDoclet2. He has been having a great time with Wicket since day one of adoption and would like to let others know how Wicket succeeds in bringing back the fun that has been missing in the Java web development space. He also contributed to the Wicket project through the Wicket-Spring integration module using Jakarta Commons Attributes.

Source of This Material

Pro Wicket
By Karthik Gurumurthy

Published: September 2006, Paperback: 328 pages
Published by Apress
ISBN: 1-59059-722-2
Price: $39.99
eBook Price: $20.00
This material is from Chapter 1 of the book.
Reprinted with the publisher's permission.



Page 6 of 6



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel