### Clone Wicket Tutorial Examples Repository Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/howToSource.adoc Use this command to get a local copy of the Wicket tutorial examples from GitHub. ```bash git clone https://github.com/bitstorm/Wicket-tutorial-examples.git ``` -------------------------------- ### Install Graphite on Mac using Homebrew Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/monitoring/monitoring_2.adoc These commands provide a quick setup guide for installing Graphite and its dependencies on a macOS system using Homebrew and pip. Remember to adjust ownership and configuration files as indicated. ```bash brew install python ``` ```bash brew install cairo ``` ```bash brew install py2cairo ``` ```bash pip install Django==1.5 ``` ```bash pip install "django-tagging<0.4" ``` ```bash sudo pip install carbon ``` ```bash pip install whisper ``` ```bash sudo pip install graphite-web ``` ```bash sudo pip install Twisted==11.1.0 ``` ```bash sudo chown -R :staff /opt/graphite ``` ```bash cp /opt/graphite/conf/carbon.conf{.example,} ``` ```bash cp /opt/graphite/conf/storage-schemas.conf{.example,} ``` ```bash cd /opt/graphite/webapp/graphite ``` ```bash cp local_settings.py{.example,} ``` ```bash python manage.py syncdb ``` ```bash python /opt/graphite/bin/carbon-cache.py start ``` ```bash python /opt/graphite/bin/run-graphite-devel-server.py /opt/graphite ``` -------------------------------- ### Preview Wicket Guide Changes Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/contributing.adoc Build and preview the Wicket user guide changes by running this Maven command in the 'wicket/wicket-user-guide' directory. This command compiles the guide and generates HTML/PDF output. ```bash mvn clean package -P guide ``` -------------------------------- ### XML Resource Bundle Example Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/i18n/i18n_2.adoc An example of an XML file used as a resource bundle, containing a greeting message in simplified Chinese. Ensure the file conforms to the properties DTD and uses UTF-8 encoding. ```xml 欢迎光临本网站! ``` -------------------------------- ### Build Docker Image Source: https://github.com/apache/wicket/blob/master/wicket-examples/docker-howto.md Builds the Docker image for Wicket examples and tags it with the specified version. ```bash docker build --tag apache.jfrog.io/wicket-docker/wicket-examples:LATEST-10 . ``` -------------------------------- ### Install Wicket feature in Karaf Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/karaf/karaf_1.adoc Install the 'wicket-core' feature into your running Karaf instance. This makes Wicket available for use. ```bash karaf@root()> feature:install wicket-core ``` -------------------------------- ### Basic Wicket Page Rendering Test Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/testing/testing_1.adoc This snippet demonstrates the fundamental setup for Wicket unit testing. It initializes WicketTester and asserts that the home page renders successfully without errors. Use this as a starting point for most Wicket tests. ```java class TestHomePage{ private WicketTester tester; @BeforeEach void setUp(){ tester = new WicketTester(new WicketApplication()); } @Test void homepageRendersSuccessfully(){ //start and render the test page tester.startPage(HomePage.class); //assert rendered page class tester.assertRenderedPage(HomePage.class); } } ``` -------------------------------- ### Static Label Example Source: https://github.com/apache/wicket/blob/master/wicket-examples/src/main/java/org/apache/wicket/examples/compref/LabelPage.html Displays static text directly on the page. This is the simplest form of a label. ```html this text will be replaced ``` -------------------------------- ### Launch JNLP Application with JavaScript Source: https://github.com/apache/wicket/blob/master/wicket-core-tests/src/test/java/org/apache/wicket/markup/MarkupParserTest_7.html This script launches a JNLP application. It checks for Gecko-based browsers or if Java Web Start is installed to determine the launch method. If neither condition is met, it provides instructions to download and install the JRE. ```javascript //Launch the application"); } else { document.write("Click "); document.write("here "); document.write("to download and install JRE 5.0 and the application."); } // it mustnt break if the string contains the cdata end marker ]] var test1="some]]>"; //]]> ``` -------------------------------- ### Example URL for a Package-Mounted Page Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/urls/urls_6.adoc Demonstrates the URL structure for a specific page within a package that has been mounted. The URL includes the base mounted path and the page's class name. ```html /mountPackage/StatefulPackageMount?1 ``` -------------------------------- ### Configure Wicket Deployment Mode via System Property Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/maven/maven_1.adoc Set Wicket to run in deployment mode by specifying the system property '-Dwicket.configuration=deployment' when starting the server. ```java java -Dwicket.configuration=deployment ... ``` -------------------------------- ### Verify Wicket feature installation in Karaf Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/karaf/karaf_1.adoc Check if the Wicket feature is available in your Karaf environment. This command lists all installed features and filters for 'wicket'. ```bash karaf@root()> feature:list | grep -i wicket wicket-core │ _version_ │ │ Uninstalled │ org.apache.wicket.wicket-_version_ │ ``` -------------------------------- ### Set and Get Indexed PageParameters Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/urls/urls_1.adoc Demonstrates how to set indexed parameters and retrieve their values using PageParameters. ```java PageParameters pageParameters = new PageParameters(); //add a couple of parameters pageParameters.set(0, "foo"); pageParameters.set(1, "bar"); //retrieve the value of the second parameter ("bar") pageParameters.get(1); ``` -------------------------------- ### Bookmarkable URL with Named Parameters Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/urls/urls_1.adoc Example of a generated bookmarkable URL that includes named query string parameters. ```html /PageParametersExample/wicket/bookmarkable/ org.wicketTutorial.PageWithParameters?foo=foo&bar=bar ``` -------------------------------- ### Wicket Component Queuing Example Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/componentQueueing/componentQueueing_4.adoc Demonstrates how to queue components in Wicket, including nested components within a container. Ensure components are queued to their intended parent or ancestor to maintain security and structure. ```java queue(new Label("first")); queue(new Label("last")); WebMarkupContainer secure=new WebMarkupContainer("secure") { void onConfigure() { super.onConfigure(); setVisible(isViewingOwnProfile()); } }; queue(secure); secure.queue(new Label("creditCardNumber")); secure.queue(new Label("creditCardExpiry")); ``` -------------------------------- ### HTML Markup for List/Detail View Page Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/modelsforms/modelsforms_6.adoc This is the HTML structure for the example page, defining a dropdown for persons and a form for editing their details. ```html List of persons

Name:
Surname:
Address:
Email:
``` -------------------------------- ### Basic Link Example Source: https://github.com/apache/wicket/blob/master/wicket-examples/src/main/java/org/apache/wicket/examples/compref/LinkPage.html Demonstrates a basic Wicket link attached to an anchor element. This is used for standard navigation or triggering actions. ```html [this link is clicked n times](#) ``` -------------------------------- ### Get and Set Resource Stream Locator Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/resources/resources_14.adoc Demonstrates how to retrieve the current resource locator and set a custom one using ResourceSettings. This is typically done during application initialization. ```java //init application's method @Override public void init(){ //get the resource locator getResourceSettings().getResourceStreamLocator(); //set the resource locator getResourceSettings().setResourceStreamLocator(myLocator); } ``` -------------------------------- ### Inspect Wicket feature details in Karaf Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/karaf/karaf_1.adoc Use this command to get detailed information about the 'wicket-core' feature, including its bundles and dependencies. This is useful for troubleshooting. ```bash karaf@root()> feature:info wicket-core Feature wicket-core _version_ Feature has no configuration Feature has no configuration files Feature has no dependencies. Feature contains followed bundles: ... _wicket dependency bundles_ ... mvn:org.apache.wicket/wicket-util/_version_ mvn:org.apache.wicket/wicket-request/_version_ mvn:org.apache.wicket/wicket-core/_version_ mvn:org.apache.wicket/wicket-auth-roles/_version_ mvn:org.apache.wicket/wicket-devutils/_version_ mvn:org.apache.wicket/wicket-extensions/_version_ mvn:org.apache.wicket/wicket-jmx/_version_ Feature has no conditionals. ``` -------------------------------- ### JavaScript Module Imports Source: https://github.com/apache/wicket/blob/master/wicket-core-tests/src/test/java/org/apache/wicket/markup/parser/filter/PageWithScriptTemplate.html Example of how to define module imports for JavaScript, specifying local and remote module paths. ```javascript { "imports": { "square": "./module/shapes/square.js", "circle": "https://example.com/shapes/circle.js" } } ``` -------------------------------- ### Generated URL with Placeholder Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/urls/urls_6.adoc Example of a generated URL when using a parameter placeholder. The placeholder value is inserted into the URL path. ```html /pageMount/foo/otherSegm ``` -------------------------------- ### Wicket ID Naming Example Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_3.adoc Demonstrates correct Wicket ID naming by including only the business aspect. This avoids redundancy with technical details present in both HTML and Java code. ```java new TextField("birthdate") ``` -------------------------------- ### Bad Practice: Passing Page to Constructor Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_10.adoc Avoid passing entire components or pages to constructors. This example shows a 'SettingsPage' that accepts a 'backToPage' argument, leading to tight coupling and predetermined instantiation order. ```java // Bad solution public class SettingsPage extends Page { public SettingsPage (IModel settingsModel, final Webpage backToPage) { Form form = new Form("form"); // add components form.add(new SubmitButton("changeSettings") { public void onSubmit() { // do something setResponsePage(backToPage); } }); add(form); } } ``` -------------------------------- ### Wicket Component Factory Pattern Example Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_12.adoc Demonstrates a factory pattern for creating Wicket Label components. This approach has limitations regarding inheritance and overriding component lifecycle methods. ```java public class CmsFactory { public Label getCmsLabel(String markupId, final String url) { IModel fragment = () -> loadSomeContent(url); Label result = new Label(markupId, fragment); result.setRenderBodyOnly(true); result.setEscapeModelStrings(false); return result; } public String loadContent(String url) { // load some content } } // create the component within the page: public class MyPage extends WebPage { @SpringBean CmsFactory cmsFactory; public MyPage() { add(cmsFactory.getCmsLabel("id", "http://url.to.load.from")); } } ``` -------------------------------- ### Original Wicket Java Hierarchy Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/componentQueueing/componentQueueing_1.adoc This Java code represents the initial setup of Wicket components before introducing a new container. ```java Form form = new Form<>("customer"); add(form); form.add(new TextField("first")); form.add(new TextField("last")); ``` -------------------------------- ### StatelessLink Example with Instance Variable Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/urls/urls_5.adoc Illustrates a potential issue where instance variables in onClick() of a StatelessLink may not behave as expected due to page re-instantiation. The printed value will always be zero. ```java public class StatelessPage extends WebPage { private int index = 0; public StatelessPage(PageParameters parameters) { super(parameters); } @Override protected void onInitialize() { super.onInitialize(); setStatelessHint(true); add(new StatelessLink("statelessLink") { @Override public void onClick() { //It will always print zero System.out.println(index++); } }); } } ``` -------------------------------- ### Mount Resource Reference with Lambda Supplier Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/resources/resources_12.adoc Lambda expressions are useful with ResourceReference factory methods like 'of' that accept a resource supplier. This example shows how to mount a resource defined by a lambda. ```java @Override public void init() { super.init(); IResource helloWorldRes = (attributes) -> attributes.getResponse().write("Hello world!"); ResourceReference resRef = ResourceReference.of("helloworld", () -> helloWorldRes); mountResource("/helloworld", resRef); } ``` -------------------------------- ### Model-Bound Visibility Control Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_5.adoc Configure component visibility based on its model's state. This example makes a Label visible only if its text starts with 'Berlusconi'. ```java new Label("headline", headlineModel) { @Override public void onConfigure() { // Headline visible only if text starts with "Berlusconi" String headline = getModelObject(); setVisible(headline.startsWith("Berlusconi")); } } ``` -------------------------------- ### Basic REST Resource Implementation Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/wicketstuff/wicketstuff_6.adoc Demonstrates mapping methods to specific subpaths and HTTP methods using @MethodMapping. ```APIDOC ## GET /persons ### Description Retrieves a list of all persons. ### Method GET ### Endpoint /persons ### Request Body None ### Response #### Success Response (200) - **List** (List) - A list of PersonPojo objects. #### Response Example ```json [ { "name": "John Doe", "age": 30 } ] ``` ## DELETE /persons/{personIndex} ### Description Deletes a person identified by their index. ### Method DELETE ### Endpoint /persons/{personIndex} ### Parameters #### Path Parameters - **personIndex** (int) - Required - The index of the person to delete. ### Response #### Success Response (200) - No content is returned upon successful deletion. ## POST /persons ### Description Creates a new person resource. ### Method POST ### Endpoint /persons ### Request Body - **personPojo** (PersonPojo) - Required - The data for the new person. ### Request Example ```json { "name": "Jane Doe", "age": 25 } ``` ### Response #### Success Response (200) - No content is returned upon successful creation. ``` -------------------------------- ### Wicket AJAX JavaScript Call Example Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/ajax/ajax_5.adoc This is an example of the final AJAX function generated for a behavior used in the AjaxEventBehavior project. It shows the parameters passed to Wicket.Ajax.ajax. ```javascript Wicket.Ajax.ajax({"u":"./?0-1.IBehaviorListener.0-clickCounterLabel", "e":"click", "c":"clickCounterLabel1"}); ``` -------------------------------- ### Setup DropDownChoice with Localized Display Values in Wicket Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/i18n/i18n_4.adoc Override localizeDisplayValues to return true to enable localization of choice display values. This setup is for a DropDownChoice component that displays colors. ```java public HomePage(final PageParameters parameters) { super(parameters); List locales = Arrays.asList(Locale.ENGLISH, Locale.ITALIAN, Locale.GERMAN); List colors = Arrays.asList("green", "red", "blue", "yellow"); final DropDownChoice changeLocale = new DropDownChoice("changeLocale", new Model(), locales); StatelessForm form = new StatelessForm("form"){ @Override protected void onSubmit() { Session.get().setLocale(changeLocale.getModelObject()); } }; DropDownChoice selectColor = new DropDownChoice("selectColor", new Model(), colors){ @Override protected boolean localizeDisplayValues() { return true; } }; form.add(selectColor); add(form.add(changeLocale)); } ``` -------------------------------- ### Using DataGrid with ListDataProvider Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/wicketstuff/wicketstuff_5.adoc Illustrates how to instantiate and configure a DataGrid component using a ListDataProvider and defining columns. Ensure the Person list is loaded before creating the ListDataProvider. ```html ...
Grid
... ``` ```java final List personList = //load a list of Persons final ListDataProvider listDataProvider = new ListDataProvider(personList); //define grid's columns List cols = (List) Arrays.asList( new PropertyColumn(new Model("First Name"), "firstName"), new PropertyColumn(new Model("Last Name"), "lastName")); DataGrid grid = new DefaultDataGrid("grid", new DataProviderAdapter(listDataProvider), cols); add(grid); ``` -------------------------------- ### Declare JavaScript and CSS Resource Bundles Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/resources/resources_7.adoc Initialize resource bundles for JavaScript and CSS during application startup. Ensure each resource reference is unique to a single bundle. ```java getResourceBundles().addJavaScriptBundle(WicketApplication.class, "jqueryUiJs", jqueryJsReference, jqueryUiJsReference); getResourceBundles().addCssBundle(WicketApplication.class, "jqueryUiCss", jqueryCssReference, jqueryUiCssReference); ``` -------------------------------- ### Wicket Model Inheritance Pitfall Example Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/modelsforms/modelsforms_4.adoc This example demonstrates a potential pitfall with CompoundPropertyModel where nested containers without their own models can lead to unexpected property expressions. The 'name' label inherits the page's model, but the 'spouse' container's ID is ignored in the property expression. ```java //Create a person named 'John Smith' Person person = new Person("John", "Smith"); //Create a person named 'Jill Smith' Person spouse = new Person("Jill", "Smith"); //Set Jill as John's spouse person.setSpouse(spouse); defaultModel(new CompoundPropertyModel(person)); WebMarkupContainer spouseContainer = new WebMarkupContainer("spouse"); Label name; spouseContainer.add(name = new Label("name")); add(spouseContainer); ``` -------------------------------- ### HTML Markup for Label Example Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/componentLifecycle/componentLifecycle_4.adoc The associated HTML markup for the Label component that will be modified by onComponentTag. ```html

``` -------------------------------- ### Simulating Link Clicks and Asserting Label Text Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/testing/testing_1.adoc This example shows how to simulate a user clicking a link and then verify that a specific label's text has updated as expected. It uses `clickLink` to trigger an action and `assertLabel` to check the result. Ensure the component paths are correct for your application. ```java //... @Test void switchLabelTest(){ //start and render the test page tester.startPage(HomePage.class); //assert rendered page class tester.assertRenderedPage(HomePage.class); //assert rendered label tester.assertLabel("label", "First label"); //simulate a click on "reload" button tester.clickLink("reload"); //assert rendered label tester.assertLabel("label", "Second label"); } //... ``` -------------------------------- ### Good Practice: Using a Hook for Navigation Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_10.adoc This solution uses the Hollywood principle by introducing an abstract method 'onSettingsChanged()' as a hook. This decouples the 'SettingsPage' from the specific page it redirects to, improving flexibility and reusability. ```java // Good solution public class SettingsPage extends Page { public SettingsPage (IModel settingsModel) { Form form = new Form("form"); // add components form.add(new SubmitButton("changeSettings") { public void onSubmit() { // do something onSettingsChanged(); } }); add(form); } // hook protected void onSettingsChanged() { } // The usage of the new component Link settings = new Link("settings") { public void onClick() { setResponsePage(new SettingsPage(settingsModel) { @Override protected void onSettingsChanged() { // reference to the current page setResponsePage(this); } }); } }; add(settings); ``` -------------------------------- ### Wicket Enclosure Markup Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/componentQueueing/componentQueueing_2.adoc Example of Wicket markup using the 'enclosure' attribute to group components. ```xml ``` -------------------------------- ### Autonomous Component Visibility with onConfigure() Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_5.adoc Use the onConfigure() method to allow components to manage their own visibility. This approach centralizes logic and avoids manual state management, making it more robust. ```java public class LoginBoxPanel { // constructor etc. @Override public void onConfigure() { setVisible(MySession.get().isNotLoggedIn()); } } ``` -------------------------------- ### Initialize Wicket HTTP/2 Settings with Custom PushBuilder Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/http2push/http2push_2.adoc This Initializer class sets up Wicket's HTTP/2 settings by providing a custom PushBuilder implementation. Ensure this class is correctly registered in META-INF/services/org.apache.wicket.IInitializer. ```java public class Initializer implements IInitializer { /** * Initializes the push builder API of Jetty 9.3+ */ @Override public void init(Application application) { Http2Settings http2Settings = Http2Settings.Holder.get(application); http2Settings.setPushBuilder(new Jetty9PushBuilder()); } @Override public void destroy(Application application) { // NOOP } } ``` -------------------------------- ### Create a Main Initializer to Orchestrate Others Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/advanced/advanced_4.adoc Use a main initializer to call the init methods of other initializers, allowing for multiple configurations. ```java public class MainInitializer implements IInitializer{ public void init(Application application) { new AnotherInitializer().init(application); new YetAnotherInitializer().init(application); //... } //destroy... } ``` -------------------------------- ### HTML Markup for Wicket Component Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/keepControl/keepControl_8.adoc This is the example HTML markup that includes a Wicket component with the `wicket:id` attribute. ```html Hello world page
[helloWorld]
``` -------------------------------- ### Append JavaScript via AJAX Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/ajax/ajax_1.adoc Appends custom JavaScript code to the AJAX response, for example, to display an alert box. ```java new AjaxLink("ajaxLink"){ @Override public void onClick(AjaxRequestTarget target) { target.appendJavaScript(";alert('Hello!!');"); } }; ``` -------------------------------- ### Get Required WebApplicationContext Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/testingspring/testingspring_2.adoc Retrieves the WebApplicationContext from the ServletContext. Throws an IllegalStateException if no context is found, typically indicating a missing ContextLoaderListener. ```java public static WebApplicationContext getRequiredWebApplicationContext(ServletContext sc) throws IllegalStateException { WebApplicationContext wac = getWebApplicationContext(sc); if (wac == null) { throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?"); } return wac; } ``` -------------------------------- ### Configure Wicket Deployment Mode via Context Parameter Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/maven/maven_1.adoc Set Wicket to run in deployment mode by defining a context parameter named 'configuration' with the value 'deployment'. ```html configuration deployment ``` -------------------------------- ### Generated URL with Encoded Parameters Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/urls/urls_6.adoc Example of a generated URL showing how page parameters are encoded as URL segments when using UrlPathPageParametersEncoder. ```html /mountedPath/foo/foo/bar/bar?1 ``` -------------------------------- ### Configure Basic Video Settings in Wicket Source: https://github.com/apache/wicket/blob/master/wicket-examples/src/main/java/org/apache/wicket/examples/media/Home.html Use this to set autoplay, controls, looping, and dimensions for a video. The width and height are null by default. Set readBuffered(false) to avoid storing the media file in memory. ```java PackageResourceReference reference = new PackageResourceReference(MyPage.class, "myVideo.mp4"); Video video = new Video("myVideo", reference); video.setAutoplay(false); video.setControls(true); video.setLooping(false); video.setWidth(320); video.setHeight(240); video.setBuffered(false); ``` -------------------------------- ### Adding DisableComponentListener to AjaxButton Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/ajax/ajax_6.adoc Example of how to add a custom DisableComponentListener to an AjaxButton's attributes to manage component state during AJAX calls. ```java //... new AjaxButton("ajaxButton"){ @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); attributes.getAjaxCallListeners().add(new DisableComponentListener(form)); } } //... ``` -------------------------------- ### Configure Picture Component with Sources and Fallback Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/resources/resources_3.adoc Use the Picture component to provide responsive images with multiple sources and a fallback image. Configure Source components with resource references and media attributes. ```java Picture picture = new Picture("picture"); Source big = new Source("big", new PackageResourceReference(getClass(), "big.jpg"), new PackageResourceReference(getClass(), "big-hd.jpg")); big.setXValues("1x","2x"); big.setMedia("(min-width: 40em)"); picture.add(big); Source small = new Source("small", new PackageResourceReference(getClass(), "small.jpg"), new PackageResourceReference(getClass(), "small-hd.jpg")); small.setXValues("1x","2x"); picture.add(small); Image image = new Image("fallback", new PackageResourceReference(getClass(), "fallback.jpg")); picture.add(image); this.add(picture); ``` -------------------------------- ### Basic AJAX Link onClick Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/ajax/ajax_1.adoc An example of an AjaxLink's onClick method, which is executed on AJAX request. Requires an instance of AjaxRequestTarget. ```java new AjaxLink("ajaxLink"){ @Override public void onClick(AjaxRequestTarget target) { //some server side code... } }; ``` -------------------------------- ### Registering a Custom Crypt Factory Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/security/security_4.adoc Demonstrates how to set a custom ICryptFactory at the application level using SecuritySettings. This is useful for integrating stronger or different cryptography mechanisms. ```java @Override public void init() { super.init(); getSecuritySettings().setCryptFactory(new SomeCryptFactory()); setRootRequestMapper(new CryptoMapper(getRootRequestMapper(), this)); } ``` -------------------------------- ### Execute Wicket Ajax Request Source: https://github.com/apache/wicket/blob/master/wicket-core-tests/src/test/java/org/apache/wicket/ajax/DomReadyOrderPage_ajax_expected.html Initiates a Wicket Ajax request. This example triggers a 'click' event on an element with ID 'test1'. ```javascript (function(){Wicket.Ajax.ajax({"u":"./org.apache.wicket.ajax.DomReadyOrderPage?0-1.0-test","c":"test1","e":"click","pd":true});})(); ``` -------------------------------- ### WicketStuff Module Structure Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/wicketstuff/wicketstuff_1.adoc Illustrates the typical directory structure of a WicketStuff module, consisting of a parent project, the main module, and an example module. ```text -parent | +--- \----examples ``` -------------------------------- ### Structure BlogEditPage Component in Java Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_15.adoc Example of structuring a Wicket page by extracting form elements into separate methods. This promotes modularity and readability. ```java public class BlogEditPage extends WebPage { private IModel blogModel; public BlogEditPage(IModel blogModel) { super(new PageParameters()); this.blogModel = blogModel; add(createBlogEditForm()); } private Form createBlogEditForm() { Form form = newBlogEditForm(); form.add(createHeadlineField()); form.add(createContentField()); form.add(createTagField()); form.add(createViewRightPanel()); form.add(createCommentRightPanel()); form.setOutputMarkupId(true); return form; } // more methods here } ``` -------------------------------- ### Configure Video with Source Tags and Media Queries in Wicket Source: https://github.com/apache/wicket/blob/master/wicket-examples/src/main/java/org/apache/wicket/examples/media/Home.html Add multiple source tags to a video and apply media queries to display different videos based on screen resolution. This allows for responsive video delivery. ```java PackageResourceReference reference1 = new PackageResourceReference(MyPage.class, "video_small.mp4"); Source source1 = new Source(reference1); source1.setMedia("(max-width: 600px)"); PackageResourceReference reference2 = new PackageResourceReference(MyPage.class, "video_large.mp4"); Source source2 = new Source(reference2); source2.setMedia("(min-width: 601px)"); Video video = new Video("myVideo", source1, source2); video.setControls(true); ``` -------------------------------- ### Trigger Deferred Ajax Request Source: https://github.com/apache/wicket/blob/master/wicket-core-tests/src/test/java/org/apache/wicket/markup/head/filter/DeferredPage_AjaxExpected.html Initiates an Ajax request to the server for deferred rendering. This example shows a click event triggering the request. ```javascript (function(){ Wicket.Ajax.ajax({"u":"./page?0-1.0-c","c":"c1","e":"click"}); })(); ``` -------------------------------- ### Get Application Metadata (Java) Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/requestProcessing/requestProcessing_4.adoc Retrieves a previously stored java.sql.Connection object from the application's metadata store using its specific MetaDataKey. ```java Connection connection = Application.get().getMetaData(MetaDataApp.connectionKey); ``` -------------------------------- ### Get Current RequestCycle in Wicket Component Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/requestProcessing/requestProcessing_3.adoc A convenience method within a Wicket Component to retrieve the current RequestCycle. It internally calls RequestCycle.get(). ```java public final RequestCycle getRequestCycle() { return RequestCycle.get(); } ``` -------------------------------- ### Wicket Component Hierarchy Solution Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/componentQueueing/componentQueueing_2.adoc Shows how using 'queue' instead of 'add' correctly inserts auto components into the Java hierarchy, resolving visibility and validation issues. ```java queue(new TextField("first").setRequired(true).setVisible(false)); queue(new TextField("last").setRequired(true)); ``` -------------------------------- ### Generated URL with Missing Optional Placeholder Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/urls/urls_6.adoc Example of a generated URL when an optional parameter is missing. The URL segment corresponding to the optional placeholder is omitted. ```html /pageMount/otherSegm ``` -------------------------------- ### Mount Page with Parameter Placeholder Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/urls/urls_6.adoc Define a URL path with a dynamic segment using ${placeholderName}. This segment will be populated by the named parameter when the page is instantiated. ```java mountPage("/pageMount/${foo}/otherSegm", MountedPageWithPlaceholder.class); ``` -------------------------------- ### Create ResourceModel with Key Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/i18n/i18n_5.adoc Use ResourceModel to retrieve a string resource based on a given key. This is suitable for simple, static resource lookups. ```java new ResourceModel("greetingMessage"); ``` -------------------------------- ### Implement Single Checkbox Form in Wicket Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/forms2/forms2_11.adoc This example demonstrates how to create a form with a single CheckBox component, linking it to a boolean property in a model object. ```html
Name:
Surname:
Address:
Email:
Subscribe list:
``` ```java public HomePage(final PageParameters parameters) { RegistrationInfo registrationInfo = new RegistrationInfo(); registrtionInfo.setSubscribeList(true); Form form = new Form<>("form", new CompoundPropertyModel(registrtionInfo)); form.add(new TextField("name")); form.add(new TextField("surname")); form.add(new TextField("address")); form.add(new TextField("email")); form.add(new CheckBox("subscribeList")); add(form); } ``` -------------------------------- ### Timed Ajax Update for Component Source: https://github.com/apache/wicket/blob/master/wicket-core-tests/src/test/java/org/apache/wicket/ajax/markup/html/componentMap/SimpleTestPageExpectedResult.html Initiates a timed Ajax update for a specific Wicket component. This example updates the component every 2 seconds. ```javascript Wicket.Event.add(window, "load", function(event) { Wicket.Timer.set('linja11.0', function(){Wicket.Ajax.ajax({"u":"./org.apache.wicket.ajax.markup.html.componentMap.SimpleTestPage?0-1.0-testPanel-baseSpan-linja1","c":"linja11"});}, 2000);; ;}); ``` -------------------------------- ### StringResourceModel with Component and Model Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/i18n/i18n_5.adoc Instantiate StringResourceModel specifying the resource key, a component for bundle lookup, and a model for dynamic data. This allows for custom bundle selection. ```java new StringResourceModel("myKey", myComponent, myModel); ``` -------------------------------- ### Java Code for WebMarkupContainer Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/keepControl/keepControl_4.adoc This Java code demonstrates initializing a WebMarkupContainer, adding a Label to it, and managing its visibility. Use this for components that are tightly coupled to a specific page's markup. ```java //Page initialization code WebMarkupContainer informationBox = new WebMarkupContainer ("informationBox"); informationBox.add(new Label("messagesNumber", messagesNumber)); add(informationBox); //If there are no new messages, hide informationBox informationBox.setVisible(false); ``` -------------------------------- ### Trigger Wicket Ajax Request Source: https://github.com/apache/wicket/blob/master/wicket-core-tests/src/test/java/org/apache/wicket/TestDetachPageAjaxResult.html Initiates an AJAX request using Wicket's JavaScript API. This example triggers a click event on a component. ```javascript (function(){Wicket.Ajax.ajax({"u":"./org.apache.wicket.TestDetachPage?0-1.0-comp","c":"comp1","e":"click"});})(); ``` -------------------------------- ### Implement Wicket IInitializer Interface Source: https://github.com/apache/wicket/blob/master/wicket-user-guide/src/main/asciidoc/advanced/advanced_4.adoc Implement the init(Application) method for initialization code and destroy(Application) for cleanup when the application terminates. ```java public class MyInitializer implements IInitializer{ public void init(Application application) { //initialization code } public void destroy(Application application) { //code to execute when application is terminated } } ```