Blog

You are browsing the archive for wicket.

Review Wicket in Action

June 23, 2009

In my search for new frameworks to try out, I came across a little web framework called Wicket. The idea to really separate the logic from the markup appealed to me, as well as the fact that you wouldn’t need as much JavaScript anymore. So I went looking for a book about the subject and found Wicket in Action written by some of the core contributors to Wicket. It was a tough job summarizing the book as it is crammed with lots of examples about what you can do with it. So please forgive me if the following is a bit dry, I can assure you that the book itself isn’t!

Part 1 Getting started with Wicket
This part of the book contains a quick introduction to Wicket so you can get started.

What is Wicket
Wicket is an open source web-application framework for the Java platform, which bridges the impedance mismatch between the stateless HTTP and stateful server-side programming in Java by providing a programming model that hides the fact that you’re working on a stateless protocol. With Wicket, you program in just Java and just HTML using meaningful abstractions.

The architecture of Wicket
The architecture of Wicket revolves around several objects that play a central role in request processing: Application, Session, SessionStore, Request, Response, RequestCycle, RequestCycleProcessor and RequestTarget. When Wicket determines that it should handle a request, it delegates the processing to a request-cycle object. The processing is done in four consecutive steps: decode request, determine request target, process events and respond.
In order to build applications, you would like to reuse as much as possible, so you don’t have to reinvent everything. To this end there are many Wicket components. Each of these components consists of three parts, also known as the component triad: the markup, the Java component and the model. The markup is only concerned with presentation, you’ll find no logic in it. The UI logic is encoded in the Java components. Models are optional and are an indirection for how to get the data that drives the Java components. Typically, components are meant for one purpose. Labels render text. Text fields handle text input. Repeaters repeat elements, and so forth. But in many cases, you want to use a certain component but add functionality that isn’t related to its core function. This is where behaviors come in, they allow you to extend components using composition. Behaviors are mainly used for —but aren’t limited to— modifying attributes of HTML tags and responding to events or calls to the components they’re bound to (their host components).

Building a cheesy Wicket application
In this chapter the presented knowledge is used to build a first application.

Part 2 Ingredients for your Wicket applications
In this part of the book several components, models and behaviors are introduced.

Understanding models
Models separate your domain layer from things in the view layer, but also bind them together to make a cohesive and neatly layered structure. Models are arguably the most crucial part of Wicket to understand because they can significantly affect your application’s performance and memory requirements. Because Wicket models mediate between the view and domain layer, they enable you to apply transformations on your data before you display it, or before you accept user input and propagate it to your domain layer. All components have a model property. Not all components do something with their model: several components work fine with no model value. From the point of view of the component, IModel acts as a bean property: it has a getter and a setter. Depending on the model implementation, the value can be local and self-contained within the model, or it can be looked up dynamically and come from a domain object. Conversely, from our point of view, the model acts as the actual value of the component. The most commonly used model classes provided by Wicket are: Model, PropertyModel, CompoundPropertyModel, LoadableDetachableModel, ResourceModel and StringResourceModel. The choice between these models depends on the requirements on the model, should it be static or dynamic, does it need to be solve serialization issues, are there lots of properties that use a model, do you need to serialize all the data in the model. Finally models can be nested to combine the advantages of several types of models.

Working with components: labels, links, and repeaters
There are many Wicket components that can be used to build your applications. This chapter discusses the most basic ones. There are several components for displaying text of which the two most important ones are Label and MultiLineLabel. Then there are three components for navigation using links, ExternalLink, BookmarkablePageLink and the special markup tag <wicket:link>. Another category of components are those to respond to client actions, namely Link, AjaxLink and AjaxFallbackLink. And the final category of the chapter contains the components for repeating markup: RepeatingView and ListView. All of these components can be hidden when necessary. The markup attributes can also be changed.

Processing user input using forms
The Form component groups controls that take user input and processes them when they’re submitted. A form has an HTML part and a Java (Wicket) part. A form is used to get input from users in the form of text fields, selection boxes, radio buttons, check boxes, buttons, and more. The form groups input controls and processes all of them together when the form is submitted. Unless told otherwise, Wicket uses the post method by default to submit forms. Wicket supports three strategies for handling form submissions, configured at the application level: no redirect, redirect to buffer, redirect to render. On the server the form submission is processed in five steps: checking required input, converting the input from string to the model type, validating the converted input, pushing the converted value to the model. A failure in any of these steps stops further processing for the field that failed. When even one field has failed any step, the last step (push input) isn’t performed for any of the fields and onError is called. After the five steps have been executed either onSubmit or onError is called.
There are many Components that can be used to let the user provide input to the form. First there are the text input components: TextField, Password and TextArea. Then there are the components that let the user select from a list of items: ListChoice, DropDownChoice, RadioChoice, ListMultipleChoice and CheckBoxMultipleChoice. For this last category it is quite common to bind the components to a model that fetches the data from some other source than the Java code. In such a case it might be convenient to use a ChoiceRenderer to bind the value and the display text to certain properties of a Java Object that represents the object. Finally there is also the CheckBox to represent boolean properties. A third category of components contains components for submitting the form data. This category contains Button, SubmitLink and AjaxSubmitLink. In order to make a cancel button, you will have to tell it to skip form processing, or in case you want to keep the values, only the validation. Then there is the validation itself. Fields can be required, and validators can be added to them. Wicket supplies a large number of validators, among them the NumberValidator, StringValidator, PatternValidator, EmailValidator, UrlValidator, EqualPasswordInputValidator. It’s also very easy to write your own validators.
The last aspect of forms is the feedback. Wicket comes with many feedback messages in various languages. The messages are provided in resource bundles and can be customized. Besides the validation messages you can add your own messages at different levels of severity (info, warn, and error). To display these messages you have to add a FeedbackPanel. The feedback panel also lets you filter for certain kinds of messages.

Composing your pages
Another issue where Wicket has lots of components to help you out is the issue of grouping and distributing components to maximize reuse and minimize maintenance costs. For grouping on pages there are three options: grouping using a WebMarkupContainer, grouping using a Panel, and grouping using a Fragment. A WebMarkupContainer groups components directly in the markup and Java code. No extra files are necessary. It should be used when the grouped components aren’t reusable, but they need to act together for Ajax updates or visibility changes. This approach is also helpful to modify attributes of a markup tag. A Panel groups components in a separate markup file and Java class. It should be used when the grouped components are to be reused in different pages, or contributions to the header are necessary. And finally a Fragment groups components in a separate component hierarchy outside the normal hierarchy, but inside the markup file. Also known as an inline panel. It should be used when the grouped components are inherent to the page/panel they’re part of and aren’t reusable in other pages/panels.
The other half of the equation in this chapter is page composition. There are three options for composition: using plain pages, using markup inheritance, and using panels. The main disadvantage of using plain pages is that all things that are on both pages have to be duplicated. With inheritance you can create a base page that contains all the components common to all pages. This base page can then put a special tag “wicket:child” in the place where the specific components have to be put for all the pages that extend the base page. All the pages that extend the base page have an element “wicket:extend” to indicate that everything between those tags has to be put in the child element. All the elements from the child page are added to the base page. This leads to problems when the child tag is wrapped in another tag, like a form. You would expect the components of the child page to be added to the form in that case, but that is not the case. This can be achieved however by turning the container into a transparent resolver. The final option is to put the common functionality in a single page and using panels to swap parts of the page with new content. To decide on which of these strategies to use there are four criteria that should be considered: previewability, duplication, navigation and bookmarkability. Since neither of the three strategies fulfills all criteria, there is no clear preferred solution.

Part 3 Going beyond Wicket basics
In this part of the book they show how to build your own components.

Developing reusable components
Wicket has a lot of abstract classes that can be used to create custom components. Making these reusable is as easy as putting the implementation code in it’s own class. Compound components can be easily created by placing components on a Panel. In order to make a compound component into a form component the FormComponentPanel has to be extended. To keep the models of the nested components and the top component synchronized, we need to override two methods: onBeforeRender, which prepares for rendering, and convertInput, which handles receiving input. onBeforeRender is defined at the level of the Component base class.

Images, CSS, and scripts: working with resources
There are some things you can’t do with Components. For example, you can’t render PDFs with them, and they don’t provide a direct answer to how images or CSS files should be handled. Therefor Wicket supports adding resources to your project. Packaged resources are resource that are packaged along with all the rest of your code, without the configuration hassle that marks most other frameworks. Packaged resources can be added to a page using auto-linking (i.e. using the wicket:link tag in the markup). WebResource is a base resource class that can be used to work with streams. To host such a resource, a ResourceLink has to be added to the page, or the resource has to be turned into a SharedResource. To implement streaming, there is also the alternative solution to set the target of an onSubmit method directly ot the ResourceStreamRequestTarget. Resources can handle requests independently and stream responses back to the client any way they like. This makes them suitable for streaming content that isn’t rendered by Wicket, but by third party libraries.

Rich components and Ajax
Ajax is an acronym for Asynchronous JavaScript and XML. It stands for a whole range of techniques that have the same goal: letting browsers perform server round-trips in the background so that web pages can be updated without doing a full reload. Wicket ships with a specialized Ajax engine designed to be used with Wicket’s server-side components and behaviors. It is designed to be as minimal as possible and thus isn’t as feature rich as some other Ajax engines. The engine is geared toward the following: message-handling between the client and the server, repainting and hiding components, executing custom JavaScript sent by Ajax responses, dynamically adding JavaScript and CSS to the page, providing the meanse to debug/track the engine’s workings, and throttling and timeout functionality. Wicket ships with quite a few high-level Ajax components, such as: AjaxLink, AjaxSubmitLink, AjaxSubmitButton, AjaxCheckBox, AjaxEditableLabel, and AutoCompleteTextField. Beside these components there are also Ajax behaviors. Ajax behaviors are created by extending AbstractAjaxBehavior. There are also some standard implementations that are shipped with wicket like: AjaxSelfUpdatingTimerBehavior, AjaxFormComponentUpdatingBehavior, AjaxFormSubmitBehavior and AjaxFormValidatingBehavior.
Contributing to the header section of pages is crucial for many components. This ability of individual components and behaviors to contribute to the page’s header is called a header contribution. One option to make a header contribution is by adding a HeaderContributor. Another option is by overriding the renderHead method in an Ajax behavior. The third option is to add the wicket:head tag to the markup.
If you want to use a third-party Ajax engine, you typically start by creating an abstract base class for that engine. That base class should extend AbstractAjaxBehavior. The minimal thing the base class then does is ensure that the proper JavaScript is contributed when the host component is rendered. You also want to be sure the common JavaScript is contributed only once for all behaviors that use the same engine, and you want to encapsulate these contributions so clients don’t have to know anything about them.

Part 4 Preparing for the real world
This final part of the book deals with some final aspects to get your application ready for the big, bad world that is out there.

Securing your application
With Wicket, if you don’t code using bookmarkable pages, you use session-relative pages. Page instances are kept on the server, and you ask Wicket (through your browser) for a certain page by providing the page number, the version, and the component that is the target of the request.
A good place to store authorization information is in the Wicket session object, because it’s available throughout the user’s session. Wicket creates sessions for users automatically. A simple form of authentication uses a sign-in page with a user name and password field in a form. It is good practice to have this form extend StatelessForm, so that the page doesn’t expire. The onSubmit method of the form should then handle the actual authentication.
Wicket uses authorization strategies to implement authorization as a cross-cutting concern. In order to create your own strategy, you have to implement IAuthorizationStrategy. One option of using such a strategy is by creating a base secured class that protected pages must extend. Another option is using annotations to mark the protected pages.
Finally the wicket-auth-roles and the WASP/SWARM projects are mentioned. Both are projects that have built standardized security mechanisms to support Wicket.

Conquer the world with l10n and i18n
Localization refers to the adaptation of your application for one or more specific locales. A related term is internationalization, which encompasses all techniques that enable applications to be localized: being able to conveniently maintain different languages, handling different date and number formats, using the proper encoding type, and so forth. For the sake of simplicity, the authors use only the term localization, even if it sometimes would be more precise to talk about internationalization. The most important aspects of localization are alphabets and scripts, and formats. To support multiple languages you can put all the locale-dependent parts in separate files and then using the wicket:message tag to look up those parts. The pattern for looking up these files is:

session = The current user session
component = The component that initiated the resource lookup
name = The name of the class of the component that is currently input for the search, starting with the name of component
style = [component.variation" "_" "[session.style" "_" "]]
ext = (”.properties” /”.xml”)
path = name["_"style["_" language["_" country]["_variant"]]]ext

Instead of using <wicket:message> tags, you could use normal Label components with a ResourceModel. Another option is to use localized markup files. The disadvantage of this however is that there will probably be a lot of duplication.
Wicket has a mechanism for handling objects that have different string representations depending on the locale. The objects responsible for such conversions in Wicket are called converters. Wicket’s default configuration is probably good for 95% of use cases. But the default configuration may be insufficient at times. If that is the case you can write a custom converter. This can be done by overriding the getConverter method in a field. Or you can create a converter locator that knows where to get converter instances for the appropriate types.

Multitiered architectures
This chapter gives an overview of how to set up Spring and Hibernate to create a multitiered architecture for your application.

Putting your application into production
Before you can put your application in production you have to test it, create a site map that is optimized for your users and search engines, and configure the application for production. Then finally you’ll want to keep an eye on it once it is in production.
In order to test you Wicket application you can use the WicketTester class combined with JUnit. This class has methods like startPage, assertLabel and onClick to test-drive the pages and components as if they were called during a normal request.
The regular session-relative requests aren’t very nice for your users, as they won’t be able to bookmark them. Search engines in particular can’t deal with them, which means that all the information in your application can’t be found. While that is sometimes a good thing, at other times it is not what you want. That is why they have provided the BookmarkablePageLink. This still doesn’t provide a URL that looks nice, but at least search engines can handle them. If you want a URL that looks nice as well, which is something that will help you score better in some search engines too, you will have to use mounting and URL encoding. Mounting is the process of converting the BookmarkablePageLink with a fully qualified classname into a specific path. Transforming something like:

http://cheesr.com/shop?wicket:bookmarkablePage=%3Acom.cheesr.shop.CheeseDetailsPage&cheese=edam

into something like:

http://cheesr.com/cheeses/cheese/edam/

By using URL encoding strategies, this can be optimized even further. Wicket provides several strategies like: QueryStringUrlEncodingStrategy, BookmarkablePageRequestTargetUrlCodingStrategy, IndexedParamUrlCodingStrategy, MixedParamUrlCodingStrategy, HybridUrlCodingStrategy and IndexedHybridUrlCodingStrategy.
Wicket applications can run in two modes: Development mode, which provides maximum developer support, and Deployment mode, which provides maximum performance and security for production. By default Wicket starts in development mode. Before going to production the mode should be switched, either through a system property, a servlet/filter-initialization parameter or a context-initialization parameter. All of the options that are turned off by switching to deployment mode, can be turned back on again in the Application’s init method. Another part of the configuration of an application that should be done before production is providing meaningful error pages. Wicket does provide default error pages, but these don’t look very nice, so you might want to customize them. Beside the error page, the access-denied page, the internal-error page and the page-expired error page can also be customized.
Once your application is running on your server and delivering pages to visitors, you need to ensure that the application keeps running. This means monitoring the application and, when things go wrong, figuring out what happened and how to fix it. The request logger provides this information, but it does have to be enabled and configured. Another feature that Wicket has is that through the Java Management Extendsions (JMX) it allows you to look inside a running server and adjust parameters on the fly, so you can change the markup files in production without restarting the application for example.

Conclusion
Wicket in Action is the perfect book if you want to get started with Wicket. It gently guides you past all the important concepts in Wicket and gives you tons of examples to play around with. It points you in the direction of all the most important components that you might need. The code of the examples is also provided on a site accompanying the book, so you won’t have to type it all yourself. It’s also a good book if you’ve already been playing with the framework for a little while and want to really understand what it is you’re working with.

Kennissessie Wicket & Lift

June 8, 2009

From the NL-JUG newsletter:


De Java community is rijk aan webframeworks. Elk jaar duiken er een aantal nieuwe, veelbelovende frameworks op. IPROFS organiseert een openbare kennissessie omtrent twee frameworks die steeds meer in de belangstelling staan: Wicket en Lift.

Wicket probeert de impedance mismatch tussen stateless HTTP en een statefull GUI op te lossen door de componenten structuur en eventhandling van een desktop framework als Swing na te bootsen.
Lift is een webframework voor Scala (de opvolger van Java?) dat voortbouwt op inzichten uit Rails, Wicket en Django.

Programma

18.00 uur Ontvangst en eten

19.00 uur Wicket door Frank van Westerop
Naast een live demo wordt tijdens deze presentatie de Wicket aanpak en architectuur bekeken: containers, componenten en event delegation, Spring integratie en meer.
Wat zijn de sterke punten? Zijn er ook nadelen?

20.00 uur Pauze

20.15 uur Lift door Peter van Rijn
In deze presentatie zal er in een live demo een applicatie voor een boekwinkel
gebouwd worden. Als Lift echt zo goed is, zal het zich in deze praktijksessie moeten
bewijzen!

21.15 uur Afsluiting met aansluitend borrel

IPROFS is volledig gespecialiseerd in het ontwikkelen van schaalbare, enterprise Java EE oplossingen. Aan de CMS/Portal kant zijn wij gespecialiseerd in Hippo. Onze missie is om het beste Java huis van Nederland te zijn, in alle fasen van een project. Alles wat wij doen staat in het teken van Kwaliteit, Passie en Warmte.

Na deze interessante avond ben je weer helemaal op de hoogte van deze onderwerpen. Je kunt je hiervoor kosteloos opgeven tot en met 7 juni 2009 door een e-mail te sturen met jouw naam, het bedrijf, jouw functie en telefoonnummer naar events@iprofs.nl.
Binnen een week sturen wij jou de bevestiging van jouw aanmelding.

LOCATIE
Gebouw “De Houthof”
Claus Sluterweg 125
2012 WS Haarlem
+31 (0)23 547 63 69