Apache Wicket Reference Card
Apache Wicket Reference Card
coNteNtS iNcLuDe:
n n
About Apache Wicket Project Layout Configuring the Web Application Models Components Hot Tips and more...
Apache Wicket offers a development and deployment mode that can be configured in the web.xml file:
<context-param> <param-name>configuration</param-name> <param-value>development</param-value> </context-param>
project LAyout
The project layout most typical of Apache Wicket applications is based on the default Maven directories. Any Wicket component that requires view markup in the form of HTML needs to be side-by-side with the Java file. Using Maven however, we can separate the source directories into java/ and resources/ to give some distinction. To get started, download either the wicket-quickstart project and modify it to your needs, or use the maven archetype here:
mvn archetype:create \ -DarchetypeGroupId=org.apache.wicket \ -DarchetypeArtifactId=wicket-archetype-quickstart \ -DarchetypeVersion=1.3.5 \ -DgroupId=com.mysticcoders.refcardmaker \ -DartifactId=refcardmaker
w ww.dzone.com
Hot Tip
Depending on your configuration needs, you can set this parameter in the web.xml as either: a context-param or init-param to the filter a command line parameter wicket.configuration by overriding Application.getConfigurationType()
MoDeLS
Apache Wicket uses models to separate the domain layer from the view layer in your application and to bind them together. Components can retrieve data from their model, and convert and store data in the model upon receiving an event. There are a variety of implementations of Model, and they all extend from the interface IModel.
Either way, if using Maven, youll need the wicket jar, and the latest slf4j jar.
<dependency> <groupId>org.apache.wicket</groupId> <artifactId>wicket</artifactId> <version>1.3.6</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.4.2</version> </dependency>
Apache Wicket
n n n n n
Authoritative content Designed for developers Written by top experts Latest tools & technologies Hot tips & examples Bonus content online New issue every 1-2 weeks
www.dzone.com
IModel
There are only two methods that a class would have to implement to be a Model, and that is getObject and setObject. getObject returns the value from the model, and setObject sets the value of the model. Your particular implementation of IModel can get data from wherever youd like; the Component in the end only requires the ability to get and set the value. Every component in Wicket has a Model: some use it, some dont, but its always there.
use an access object to return the Object associated with the Models stored identifier. LoadableDetachableModel handles the process of attaching and detaching the Object properly giving us as little overhead as possible.
coMpoNeNtS
In Wicket, Components display data and can react to events from the end user. In terms of the Model-View-Controller pattern, a Component is the View and the Controller. The following three distinct items make up every Wicket Component in some way: Java Class implementation defines the behavior and responsibilities HTML Markup defines the Components using their identifiers within view markup to determine where it shows to the end user The Model provides data to the Component Now that we have an idea about what makes up a Component, lets look at a few of the building blocks that make up the majority of our Pages. Forms and their Components are so important they have their own section.
PropertyModel
A model contains a domain object, and its common practice to follow JavaBean conventions. The PropertyModel allows you to use a property expression to access a property in your domain object. For instance if you had a model containing Person and it had a getter/setter for firstName to access this property, you would pass the String firstName to that Model.
CompoundPropertyModel
An even fancier way of using models is the CompoundPropertyModel. Since most of the time, the property identifier you would give Wicket mimics that of the JavaBean property, this Model takes that implied association and makes it work for you.
... setModel(newCompoundPropertyModel(person)); add(newLabel(firstName)); add(newLabel(lastName)); add(newLabel(address.address1)); ...
Label
When developing your application, if youd like to show text on the frontend chances are pretty good that youll be using the Label Component. A Label contains a Model object which it will convert to a String for display on the frontend.
<spanwicket:id=message>[message]</span> ... add(newLabel(message,Hello,World!));
We can see from the example above, that if we set the model with the person object using a CompoundPropertyModel, the corresponding components added to this parent Component will use the component identifiers as the property expression.
IDetachable
In order to keep domain objects around, youre either going to need a lot of memory / disk space, or devise a method to minimize what gets serialized in session. The detachable design helps you do this with minimal effort. Simply store as little as needed to reconstruct the domain object, and within the detach method that your Model overrides, null out the rest.
The first portion is an HTML template, which gives a component identifier of message which must be matched in the Java code. The Java code passes the component identifier as the first parameter.
Link
Below is a list of the different types of links, bookmarkable and non-bookmarkable, and how they are used to navigate from page-to-page.
Name Link Description If linking to another Page, it is best to use a Link in most instances: add(newLink(myLink){ publicvoidonClick(){ setResponsePage(MyNewPage.class); } } A Bookmarkable page gives you a human readable URL that can be linked to directly from outside of the application. The default look of this URL can be overridden as well see in the next section. add(newBookmarkablePageLink(myLink, MyNewPage.class); If linking to an external website that is not within your application, heres the Link component youll need and an example: add(newExternalLink(myLink,http://www. mysticcoders.com,Mystic);
LoadableDetachableModel
In order to make things easier, LoadableDetachableModel implements a very common use case for detachable models. It gives you the ability to override a few constructors and a load method, and provides automatic reattach and detach within Wickets lifecycle. Lets look at an example:
public class LoadableRefcardModel extends LoadableDetachableModel { privateLongid; publicLoadableRefcardModel(Refcardrefcard){ super(refcard); id=refcard.getId(); } publicLoadableRefcardModel(Longid){ super(); this.id=id; } protectedObjectload(){ if(id==null)returnnewRefcard(); RefcardDao dao = ... returndao.get(id); } }
BookmarkablePageLink
ExternalLink
Here we have two constructors, each grabbing the identifier and storing it with the Model. We also override the load method so that we can either return a newly created Object, or
DZone, Inc.
|
Repeaters
Due to the lack of any executable code inside of Wickets HTML templates, the method of showing lists may seem a
www.dzone.com
little counterintuitive at first. One of the simplest methods for showing a list of data is the RepeatingView. Heres an example of how to use it:
<ul> <liwicket:id=list></li> </ul> ... RepeatingViewlist=newRepeatingView(list); add(list); for(inti=1;i<=10;i++){ list.add(newLabel(list.newChildId(),Item+i)); }
create a new page, simply extend WebPage and start adding components. Most webapps will share common areas that you dont want to duplicate on every page -- this is where markup inheritance comes into play. Because every page is just a component, you can extend from a base page and inherit things like header, navigation, footer, whatever fits your requirements. Heres an example:
publicclassBasePageextendsWebPage{ ...header,footer,navigation,etc... } publicclassHomePageextendsBasePage{ ...everythingelse,thecontentofyourpages... }
This will simply print out a list from 1 to 10 into HTML. RepeatingView provides a method .newChildId() which should be used to ensure the Component identifier is unique. As your needs get more complex, this method quickly turns stale as there is a lot of setup that has to be done. Using a ListView is a great approach for managing possibly complex markup and business logic, and is more akin to other ways were asked to interact with Apache Wicket:
<ul> <liwicket:id=list><spanwicket:id=description>[descripti on]</span></li> </ul> ... ListViewlist=newListView(list,Arrays.asList(1,2,3, 4,5,6,7,8,9,10){ @Override protectedvoidpopulateItem(ListItemitem){ Stringtext=(String)item.getModelObject(); item.add(newLabel(description,text)); } }; add(list);
Everything is done similarly to how you would do it in Java, without the need for messy configuration files. If we need to offer up pages that can be referenced and copied, were going to need to utilize bookmarkable pages. The default Wicket implementation of a BookmarkablePage is not exactly easy to memorize, so in your custom Application class you can define several mount points for your pages:
// when a user goes to /about they will get directly to this page mountBookmarkablePage(/about,AboutPage.class); //thismountmakespageavailableat/blog/param0/param1/param2 andfillsPageParameterswith0-indexednumbersasthekey mount(newIndexedParamUrlCodingStrategy(/blog,BlogPage.class); // this mount makes page available at /blog?paramKey=paramValue&pa ramKey2=paramValue2 mount(newQueryStringUrlCodingStrategy(/blog,BlogPage.class);
This method, while it looks more complex, allows us a lot more flexibility in building our lists to show to the user. The two list approaches described above each suffer from some drawbacks, one of which is that the entirety of the list must be held in memory. This doesnt work well for large data sets, so if you need finer grain control on how much data is kept in memory, paging, etc., DataTable or DataView is something to look into.
In your code, youll need several ways of navigating to pages, including within Link implementations, in Form onSubmits, and for an innumerable number of reasons. Here are a few of the more useful:
//RedirecttoMyPage.class setResponsePage(MyPage.class); //Usefultoimmediatelyinterruptrequestprocessingtoperforma redirect thrownewRestartResponseException(MyPage.class); //Redirecttoaninterimpagesuchasaloginpage,keeptheURL inmemorysopagecancallcontinueToOriginalDestination() redirectToInterceptPage(LoginPage.class); //Usefultoimmediatelyinterruptrequestprocessingtoperforma redirectToInterceptPagecall thrownewRestartResponseAtInterceptPageException(MyPage.class);
Custom
The beauty of Wicket is that reuse is as simple as putting together a Panel of Components and adding it to any number of pages this could be a login module, a cart, or whatever you think needs to be reused. For more great examples of reusable components check out the wicket-extensions (http://cwiki.apache.org/Wicket/wicket-extensions.html) and wicket-stuff (http:..wicketstuff.org) projects.
Hot Tip
Since Wicket always needs a tag to bind to, even for a label, a <span> tag is sometimes easier to place into your markup; however, this can throw your CSS design off. .setRenderBodyOnly(true) can be used so the span never shows on the frontend but be careful using this with any AJAX enabled components, since it requires the tag to stick around.
MArkup
Apache Wicket does require adding some attributes and tags to otherwise pristine X/HTML pages to achieve binding with Component code. The following table illustrates the attributes available to use in your X/HTML templates, the most important and often used being wicket:id.
Attribute Name Description
wicket:id wicket:message
Used on any X/HTML element you want to bind a compoent to Used on any tag we want to fill an attribute with a resource bundle value. To use, prefix with te [attribute name]:[resource name]
www.dzone.com
The following table lists out all of the most commonly used tags in X/HTML templates with Wicket.
Tag Name wicket:panel Description This tag is used in your template to define the area associatedf with the component. Anything outside of this tags hierarchy will be ignored. It is sometimes useful to wrap each of your templates with html and body tags like so: <htmlxmlns:wicket=http://wicket.apache.org> <body> <wicket:panel> ... </wicket:panel> </body> </html> In this example, you can avoid errors showing in your IDE, and it wont affect the resulting HTML. Used in conjunction with markup inheritance. The subclassing Page will replace the tag with the output of its component Defining a page that inherits from a parent Page requires a mirroring of the relationship in your X/HTML template. As with wicket:panel, everything outside of the tags hierarchy will be ignored, and the components result will end up in the wrapping template Using this tag enables autolinking to another page without having to add BookmarkablePageLinks to the component hierarchy as this is done automatically for you. To link to the homepage from one of its subpages: <wicket:link><ahref=Homepage.html>Homepage</ a></wicket:link> Adding this to the root-level hierarchy of the template will give you access to inject code into the X/HTML <head></head> section. This tag will look for the given key in the resource bundle component hierarchy and replace the tag with the String retrieved from that bundle property. To pull the resource property page.label: <wicket:messagekey=page.label>[pagelabel]</ wicket:message> The entire contents of this tag will be removed upon running this code in the container. Its use is to ensure that the template can show design intentions such as repeated content without interfering with the resulting markup. A fragment is an inline Panel. Using a Panel requires a separate markup file, and with a fragment this block can be contained within the parent component. A convenience tag added in 1.3 that defines a block of code surrounding your component which derives its entire visibility from the enclosing component. This is useful in situations when showing multiple fields some of which may be empty or null where you dont want to add WebMarkupContainers to every field just to mimic this behavior. For example if we were printing out phone and fax: <wicket:enclosure> <tr><tdclass=label>Fax:</td><td><span wicket:id=fax>[faxnumber]</span></td></tr> </wicket:enclosure> ... add(newLabel(fax){publicbooleanisVisible() {returngetModelObjectAsString()!=null;}}); This tag is useful when you dont want to render any tags into the markup because it may cause invalid markup. Consider the following: <table> <wicket:containerwicket:id=repeater> <tr><td>1</td></tr> <tr><td>2</td></tr> </wicket:container> </table> In this instance, if we were to add any code in between the table and tr tags, it would be invalid. Wicket:container fixes that.
Form input controls can each have their own Models attached to them, or can inherit from their parent, the Form. This is usually a good place to use CompoundPropertyModel as it gets rid of a lot of duplicate code. As you can see, each input component should be added to the Form element. Wicket uses a POST to submit your form, which can be changed by overriding the Forms getMethod and returning Form.METHOD_GET. Wicket also uses a redirect to buffer implementation details of form posts which gets around the form repost popup. The following behavior settings can be changed:
Name No redirect Redirect to buffer Setting IRequestCycleSettings. ONE_PASS_RENDER IRequestCycleSettings. REDIRECT_BUFFER IRequestCycleSettings. REDIRECT_TO_RENDER Description Renders the response directly Renders the response directly to a buffer, redirects the browser and prevents reposting the form Redirects the browser directly; renders in a separate request
wicket:child wicket:extend
wicket:link
wicket:head wicket:message
Redirect to render
Components of a Form
The following table lists all the different form components available, and how to use them with Models.
Name TextField Example <inputtype=textwicket:id=firstName/> ... add(newTextField(firstName,new PropertyModel(person,firstName)); TextArea <textareawicket:id=comment></textarea> ... add(newTextArea(comment,new PropertyModel(feedback,comment)); Button <formwicket:id=form> <inputtype=submitvalue=Submit wicket:id=submit/> </form> ... Formform=newForm(form){ @Override protectedvoidonSubmit(){ System.out.println(onSubmit called); } }; add(form); form.add(newButton(submit)); CheckBoxMultipleChoice <spanwicket:id=operatingSystems> <inputtype=checkbox/>Windows<br/> <inputtype=checkbox/>OS/2Warp<br/> </span> ... add(new CheckBoxMultipleChoice(operat ingSystems,newPropertyModel(system, operatingSystems),Arrays.asList(Windows, OSX,Linux,Solaris,HP/UX, DOS))); DropDownChoice <selectwicket:id=states> <option>[state]</option> </select> ... add(newDropDownChoice(states,new PropertyModel(address,state), listOfStates));
wicket:remove
wicket:fragment
wicket:enclosure
wicket:container
forM
A Form in Wicket is a component that takes user input and processes it upon submission. This component is a logical holder of one or more input fields that get processed together. The Form component, like all others, must be bound to an HTML equivalent, in this case the <form> tag.
<formwicket:id=form> Name:<inputtype=textwicket:id=name/> <inputtype=submitvalue=Send/> </form> ... Formform=newForm(form){ @Override protectedvoidonSubmit(){
DZone, Inc.
www.dzone.com
PasswordTextField
EqualInputValidator EqualPasswordInputValidator
RadioChoice
More than one validator can be added to a component if needed. For instance, if you have a password that needs to be within the range of 6 20 characters, must be alphanumeric and is required, simply chain the needed validators above to your component. If the validators listed above dont fit your needs, Wicket lets you create your own and apply them to your components.
publicclassPostalCodeValidatorextendsAbstractValidator{ publicPostalCodeValidator(){ } @Override protectedvoidonValidate(IValidatablevalidatable){ Stringvalue=(String)validatable.getValue(); if(!postalCodeService.isValid(value)){ error(validatable); } } @Override protectedStringresourceKey(){ returnPostalCodeValidator; } @Override protectedMapvariablesMap(IValidatablevalidatable){ Mapmap=super.variablesMap(validatable); map.put(postalCode,n); returnmap; } }
SubmitLink
<formwicket:id=form> <ahref=# wicket:id=submitLink>Submit</a> </form> ... form.add(newSubmitLink(submitLink){ @Override publicvoidonSubmit(){ System.out.println(submitLink called); } });
Validation
When dealing with user input, we need to validate it against what were expecting, and guide the user in the right direction if they stray. Any user input is processed through this flow: Check that the required input is supplied Convert input values from String to the expected type Validate input using registered validators Push converted and validated input to models Call onSubmit or onError depending on the result
When Wicket has completed processing all input it will either pass control to the Forms onSubmit, or the Forms onError.. If you dont choose to override onError, youll need a way to customize the error messages that show up.
Feedback Messages
Apache Wicket offers a facility to send back messages for failed validations or flash messages to provide notification of status after submitting a form or performing some action. Wickets validators come with a default set of feedback messages in a variety of languages, which you can override in your own properties files. Heres the order Wicket uses to grab messages out of resource bundles:
Location Page class Component class Order 1 2 Description Messages Specific to a page Messages specific to a component Default application-wide message bundle Example Index.properties Index_es.properties AddressPanel_ es.properties CheckOutForm.properties RefcardApplication_es_ MX.properties RefcardApplication_ es.properties RefcardApplication. properties
During a Form submission, if youd like to pass back messages to the end user, Wicket has a message queue that you can access with any component:
info(Infomessage); warn(Warnmessage); error(Errormessage);
With that added to the queue, the most basic method of showing these to users is to use the FeedbackPanel component which you can add to your Page as follows:
|
DZone, Inc.
www.dzone.com
<divwicket:id=feedback></div> add(newFeedbackPanel(feedback));
the component to pull out the localized text. Another available option is to directly localize the filename of the markup files, i.e. HomePage_es_MX.html, HomePage.html. Your default locale will be used for HomePage.html, and if you were from Mexico, Wicket would dutifully grab HomePage_es_ MX.html.
When youd like to get them back out again, it will give you an Iterator to cycle through on the subsequent page:
getSession().getFeedbackMessages().iterator();
iNterNAtioNALizAtioN
Earlier sections touched on the order of resource bundles importance from the Page down to Wickets default application. Apache Wicket uses the same resource bundles standard in the Java platform, including the naming convention, properties file or XML file. Using ResourceBundles, you can pull out messages in your markup using <wicket:message>, or use a ResourceModel with
Hot Tip
Resources
Wickets Label component overrides the getModelObjectAsString of Component to offer you Localaware Strings output to the client, so you dont have to create your own custom converter.
recoMMeNDeD book
Wicket in Action is an authoritative, comprehensive guide for Java developers building Wicketbased Web applications. This book starts with an introduction to Wickets structure and components, and moves quickly into examples of Wicket at work. Written by two of the projects earliest and most authoritative experts, this book shows you both the how-to and the why of Wicket. As you move through the book, youll learn to use and customize Wicket components, how to interact with other technologies like Spring and Hibernate, and how to build rich, Ajax-driven features into your applications.
Using all of his accumulated skills, at the age of 24, Andrew began his consulting business, Mystic Coders, LLC. Since the inception of Mystic in 2000, Andrew has been building the business and studying finance and economics as he stays on the cutting edge of computer technology.
buy NoW
books.dzone.com/books/wicket-action
Bro
ugh
t to
you
by...
#8
z.co m
it ! V is arz
E: LUD IN C y TS bilit EN onsi NT esp CO of R in Cha and m Com reter rp Inte tor ... ore Itera tor dm dia d an Me rver tho se Me S Ob RN plate TTE Tem
n n n n n n n
ns tter Pa sign De
Cha in e of R ns spo ibil ity, con tinu ed
re le a que st an d th ndle e ha ue req r doe snt st w ith th e ha
one
e to th nce in fere ted k re s lis ctquic PA s, a es a bje ern IGN tt vid s, le O pro n pa DES sab iagram . UT fcard F) desig of Reu r ple s re ss d o ABO oke xam ents des cla ttern our (G Inv de h lem n Pa of F worl suc s: E inclu esig cts D ang attern real ern is D AN Th P obje enting 23 G patt , and a uct MM inal Design . Each m nd str tion ple CO orig ma k re con rma om ir im boo Softwa nt teC d to info the cre Clie the d Use om age nd Con () ns: d fr ente on, us ma ct cute Ori tter Com ) uple s obje nati ( +exe low l Pa eco is al rge cute ch xpla ona ed la e . Th s su . ati nb +exe bject nship form bjects Cre y ca an o tio e d to rate o d as ed rela ms, t th eate Use rith tha e tr ject bas . . ispa ns: lgo b to b er jects lly o g it stem tter many d ge a iv b sy win ona Pa ana allo traditi Rece en o ers. ral en uest ord to m betwe ctu twe req ndled in riant n. sa sed s Stru s be an . in va late catio e ha s: U ilitie psu at c invo to b llbacks es or cture the Enca quest s th ttern sponsib d ca stru nt tim lity. ling re g l Pa ship ng an tiona at varia the hand pose ssin func ueui tion iora , and re ject Pur led k roce to be ob av as q rela us p llbac be hand ed. y the Beh nships n be ed rono tionalit y need ject ed ca to from ch ne b d ca an tio You ne s need asyn func sts is couple ith o that st the rn the without n it is rela que ar ls w ate ips Reque y of re be de cilit d patte ssing entatio particul nsh or Dea e. ould ce Use to fa an r sh A hist pro implem ents its ting. n latio pe: pe used e comm voke for ec m Whe ntim s re al Sco ely toty The in exp th ueue actu d imple wid clas Pro ject ed at ru ue is are utilizing a job q of the ue C Ob ues with y e que the que g to en dg que s. B an en als xy . Job orithm be giv knowle that is terface Pro e ch : De e time g ct b n e in S r le of al ed ca to have d obje of the er mp cop pil rato ut an Exa serv nes ss S at com exec e queue comm Deco Ob confi S Cla e th B d the n . Th for de nge king leto ithin invo hm w Faca cha Sing od tory
n n n n
nd le a outc ay ha an tial hand sm hen oten ject le to . .W le p le ob tern ethod bject be ab tab pat ultip ecific o should cep n M this if the m up the s sp an ac d e ents ject ime. d is be a lem ks to se e passe de to of ob at runt handle imp b Use ec set til co t ld ch ges n A n ined being shou peats un paren ime ngua erm Whe not e la the runt or if it det ore s re uest som d tion proces e no m req g in metho cep n A e e ar a ndlin e ex ack th ther n ha rown in ndle th ll st until ptio th e ca Exce ion is sm to ha up th tered or ral un le cept echani passed avio co ex mp Beh . is en am Exa hen tion uest to has ack. W ject q cep st Ob e re e ex call le th nd th hand s to ha ct obje
ome.
upcoming titles
ServiceMix 4.0 ASP.NET MVC Framework Selenium Java Performance Tuning Oracle Berkeley DB Eclipse Plug-in Development Virtualization
Most popular
Spring Configuration jQuery Selectors Windows Powershell Dependency Injection with EJB 3 Netbeans IDE JavaEditor Getting Started with Eclipse Very First Steps in Flex
re f c
Download Now
a rd
Refcardz.com
Get
Mo
ef re R
50795
.com
ww
z w. d
Me
diato m
Me
ento
Ob
or
ject
Beh
avio
ral
P RES
succ
ess
9 781934 238660
Version 1.0
Copyright 2009 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, 2 ler nt and Clie photocopying, or otherwise, without prior written permission ConcreteHqpublisher. Reference: of the uest ( )
ern
Con
cre
teH
and () uest
1 ler
+ha
ndle
re
hand
le a
req
uest
ki by lin
ng
ww
z w.d
one
.c o
$7.95
Build
er
Meth tory Fac t eigh Flyw ter rpre Inte B tor Itera
State
algo
rit
Stra