This is an automated email from the ASF dual-hosted git repository. papegaaij pushed a commit to branch islands in repository https://gitbox.apache.org/repos/asf/wicket.git
commit d1f3b29f38894a0bef9cdf0094a78bf08a532668 Author: Emond Papegaaij <[email protected]> AuthorDate: Thu Nov 5 15:46:05 2026 +0100 Let a partial page update deliver named data to client-side code An Ajax response could carry components, header contributions and scripts, but no plain data. Client-side code that needed a value from the server had to receive it through an evaluated script, for example by appending JavaScript that stores JSON somewhere for later pickup. That mixes data with code, depends on where the script happens to run, and offers no ordering guarantee relative to the rest of the response. IPartialPageRequestHandler (and with it AjaxRequestTarget and the websocket request handler) now has addData(name, value). Each entry is written as a <data name="..."> element in the <ajax-response>. Both Ajax libraries publish it on the new topic '/ajax/call/data' with the call's attributes, the name and the value, after the components have been replaced and the scripts evaluated, and before the success handlers run. Wicket delivers the value as text and never interprets it. This adds an abstract method to IPartialPageRequestHandler, implemented in AbstractPartialPageRequestHandler, and an abstract writeData to PartialPageUpdate, implemented in XmlPartialPageUpdate. Applications that use these classes see no change. A custom implementation that does not extend those base classes has to implement the new method. The data part is the foundation for embedding JavaScript framework components, which need a result channel for server calls that is separate from scripts. Migration guide: "IPartialPageRequestHandler#addData(String, CharSequence) and PartialPageUpdate#writeData(Response, String, CharSequence) are new abstract methods. Implementations that do not extend AbstractPartialPageRequestHandler or XmlPartialPageUpdate must implement them." Co-Authored-By: Claude Opus 5.5 <[email protected]> --- .../apache/wicket/ajax/AjaxRequestHandlerTest.java | 19 ++++++ .../wicket/page/XmlPartialPageUpdateTest.java | 75 ++++++++++++++++++++++ .../wicket/ajax/res/js/wicket-ajax-jquery.js | 19 ++++++ .../org/apache/wicket/ajax/res/js/wicket-ajax.js | 19 ++++++ .../handler/AbstractPartialPageRequestHandler.java | 6 ++ .../handler/IPartialPageRequestHandler.java | 24 +++++++ .../org/apache/wicket/page/PartialPageUpdate.java | 67 ++++++++++++++++++- .../apache/wicket/page/XmlPartialPageUpdate.java | 10 +++ wicket-core/src/test/js/ajax.js | 28 ++++++++ wicket-core/src/test/js/data/ajax/dataResponse.xml | 30 +++++++++ .../src/main/asciidoc/ajax/ajax_6.adoc | 1 + 11 files changed, 297 insertions(+), 1 deletion(-) diff --git a/wicket-core-tests/src/test/java/org/apache/wicket/ajax/AjaxRequestHandlerTest.java b/wicket-core-tests/src/test/java/org/apache/wicket/ajax/AjaxRequestHandlerTest.java index c31ff83ca4..c91635e443 100644 --- a/wicket-core-tests/src/test/java/org/apache/wicket/ajax/AjaxRequestHandlerTest.java +++ b/wicket-core-tests/src/test/java/org/apache/wicket/ajax/AjaxRequestHandlerTest.java @@ -412,6 +412,25 @@ class AjaxRequestHandlerTest extends WicketTestCase assertTrue(tester.getLastResponseAsString().isEmpty()); } + @Test + void addData() + { + final MockPageWithLink page = new MockPageWithLink(); + page.add(new AjaxLink<Void>(MockPageWithLink.LINK_ID) { + + @Override + public void onClick(final AjaxRequestTarget target) { + target.addData("result", "{\"value\":42}"); + } + }); + + tester.startPage(page); + tester.clickLink(MockPageWithLink.LINK_ID); + + assertTrue(tester.getLastResponseAsString() + .contains("<data name=\"result\"><![CDATA[{\"value\":42}]]></data></ajax-response>")); + } + /** * https://issues.apache.org/jira/browse/WICKET-6808 */ diff --git a/wicket-core-tests/src/test/java/org/apache/wicket/page/XmlPartialPageUpdateTest.java b/wicket-core-tests/src/test/java/org/apache/wicket/page/XmlPartialPageUpdateTest.java index ab82a41742..8f7883f854 100644 --- a/wicket-core-tests/src/test/java/org/apache/wicket/page/XmlPartialPageUpdateTest.java +++ b/wicket-core-tests/src/test/java/org/apache/wicket/page/XmlPartialPageUpdateTest.java @@ -18,11 +18,14 @@ package org.apache.wicket.page; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.wicket.Component; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.parser.filter.HtmlHeaderSectionHandler; import org.apache.wicket.mock.MockWebResponse; +import org.apache.wicket.request.Response; import org.apache.wicket.util.tester.WicketTestCase; import org.junit.jupiter.api.Test; @@ -101,4 +104,76 @@ class XmlPartialPageUpdateTest extends WicketTestCase assertFalse(response.getTextResponse().toString().contains("notInPage"), "notInPage not written"); } + + @Test + void dataEntriesAreWrittenAfterEvaluationsInOrder() + { + PageForPartialUpdate page = new PageForPartialUpdate(); + + XmlPartialPageUpdate update = new XmlPartialPageUpdate(page); + update.addData("first", "{\"a\":1}"); + update.appendJavaScript("console.log('evaluated');"); + update.addData("second", "two"); + + MockWebResponse response = new MockWebResponse(); + update.writeTo(response, "UTF-8"); + + String text = response.getTextResponse().toString(); + assertTrue(text.endsWith("</evaluate><data name=\"first\"><![CDATA[{\"a\":1}]]></data>" + + "<data name=\"second\"><![CDATA[two]]></data></ajax-response>"), text); + } + + @Test + void dataNameIsEscapedAndCdataEndIsEncoded() + { + PageForPartialUpdate page = new PageForPartialUpdate(); + + XmlPartialPageUpdate update = new XmlPartialPageUpdate(page); + update.addData("a\"b<c", "x]]>y"); + + MockWebResponse response = new MockWebResponse(); + update.writeTo(response, "UTF-8"); + + assertTrue(response.getTextResponse() + .toString() + .contains("<data name=\"a"b<c\"><![CDATA[x]]]]><![CDATA[>y]]></data>")); + } + + @Test + void dataMakesTheUpdateNonEmpty() + { + XmlPartialPageUpdate update = new XmlPartialPageUpdate(new PageForPartialUpdate()); + assertTrue(update.isEmpty()); + + update.addData("name", ""); + + assertFalse(update.isEmpty()); + } + + @Test + void dataCannotBeAddedOnceTheResponseIsBeingWritten() + { + PageForPartialUpdate page = new PageForPartialUpdate(); + + XmlPartialPageUpdate update = new XmlPartialPageUpdate(page) + { + @Override + protected void onAfterRespond(Response response) + { + addData("allowed", "until the components are written"); + } + + @Override + protected void writeFooter(Response response, String encoding) + { + assertThrows(IllegalStateException.class, () -> addData("late", "too late")); + super.writeFooter(response, encoding); + } + }; + + MockWebResponse response = new MockWebResponse(); + update.writeTo(response, "UTF-8"); + + assertTrue(response.getTextResponse().toString().contains("<data name=\"allowed\">")); + } } diff --git a/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js b/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js index 375a15b2b0..fd677be5d1 100644 --- a/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js +++ b/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js @@ -872,6 +872,7 @@ // ... then add components, process remaining evaluations and a // possible redirect let stepIndexOfLastReplacedComponent = -1; + const dataNodes = []; for (let c = 0; c < root.childNodes.length; ++c) { const node = root.childNodes[c]; @@ -885,12 +886,18 @@ this.processHeaderContribution(context, node); } else if (node.tagName === "redirect") { this.processRedirect(context, node); + } else if (node.tagName === "data") { + dataNodes.push(node); } } if (stepIndexOfLastReplacedComponent !== -1) { this.processFocusedComponentReplaceCheck(steps, stepIndexOfLastReplacedComponent); } + for (let d = 0; d < dataNodes.length; ++d) { + this.processData(context, dataNodes[d]); + } + // add the last step, which should trigger the success call the done method on request this.success(context); @@ -973,6 +980,17 @@ Wicket.Ajax.redirect(text); }, + // Adds a closure that publishes a data entry to its subscribers + processData: function (context, node) { + context.steps.push(function (notify) { + const name = node.getAttribute("name"); + const value = Wicket.DOM.text(node); + Wicket.Event.publish(Wicket.Event.Topic.AJAX_CALL_DATA, context.attrs, name, value); + + return FunctionsExecuter.DONE; + }); + }, + // mark the focused component so that we know if it has been replaced by response processFocusedComponentMark: function (context) { context.steps.push(function (notify) { @@ -2573,6 +2591,7 @@ AJAX_CALL_AFTER : '/ajax/call/after', AJAX_CALL_FAILURE : '/ajax/call/failure', AJAX_CALL_DONE : '/ajax/call/done', + AJAX_CALL_DATA : '/ajax/call/data', AJAX_HANDLERS_BOUND : '/ajax/handlers/bound' } } diff --git a/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax.js b/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax.js index f1469d11ce..68a69ae541 100644 --- a/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax.js +++ b/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax.js @@ -1086,6 +1086,7 @@ // ... then add components, process remaining evaluations and a // possible redirect let stepIndexOfLastReplacedComponent = -1; + const dataNodes = []; for (let c = 0; c < root.childNodes.length; ++c) { const node = root.childNodes[c]; @@ -1099,12 +1100,18 @@ this.processHeaderContribution(context, node); } else if (node.tagName === "redirect") { this.processRedirect(context, node); + } else if (node.tagName === "data") { + dataNodes.push(node); } } if (stepIndexOfLastReplacedComponent !== -1) { this.processFocusedComponentReplaceCheck(steps, stepIndexOfLastReplacedComponent); } + for (let d = 0; d < dataNodes.length; ++d) { + this.processData(context, dataNodes[d]); + } + // add the last step, which should trigger the success call the done method on request this.success(context); @@ -1187,6 +1194,17 @@ Wicket.Ajax.redirect(text); }, + // Adds a closure that publishes a data entry to its subscribers + processData: function (context, node) { + context.steps.push(function (notify) { + const name = node.getAttribute("name"); + const value = Wicket.DOM.text(node); + Wicket.Event.publish(Wicket.Event.Topic.AJAX_CALL_DATA, context.attrs, name, value); + + return FunctionsExecuter.DONE; + }); + }, + // mark the focused component so that we know if it has been replaced by response processFocusedComponentMark: function (context) { context.steps.push(function (notify) { @@ -2849,6 +2867,7 @@ AJAX_CALL_AFTER : '/ajax/call/after', AJAX_CALL_FAILURE : '/ajax/call/failure', AJAX_CALL_DONE : '/ajax/call/done', + AJAX_CALL_DATA : '/ajax/call/data', AJAX_HANDLERS_BOUND : '/ajax/handlers/bound' } }; diff --git a/wicket-core/src/main/java/org/apache/wicket/core/request/handler/AbstractPartialPageRequestHandler.java b/wicket-core/src/main/java/org/apache/wicket/core/request/handler/AbstractPartialPageRequestHandler.java index accada33ff..f6ae171300 100644 --- a/wicket-core/src/main/java/org/apache/wicket/core/request/handler/AbstractPartialPageRequestHandler.java +++ b/wicket-core/src/main/java/org/apache/wicket/core/request/handler/AbstractPartialPageRequestHandler.java @@ -111,6 +111,12 @@ public abstract class AbstractPartialPageRequestHandler implements IPartialPageR getUpdate().appendJavaScript(javascript); } + @Override + public final void addData(String name, CharSequence value) + { + getUpdate().addData(name, value); + } + @Override public final void focusComponent(Component component) { diff --git a/wicket-core/src/main/java/org/apache/wicket/core/request/handler/IPartialPageRequestHandler.java b/wicket-core/src/main/java/org/apache/wicket/core/request/handler/IPartialPageRequestHandler.java index 4db9e986b1..bf4261e3f6 100644 --- a/wicket-core/src/main/java/org/apache/wicket/core/request/handler/IPartialPageRequestHandler.java +++ b/wicket-core/src/main/java/org/apache/wicket/core/request/handler/IPartialPageRequestHandler.java @@ -99,6 +99,30 @@ public interface IPartialPageRequestHandler extends IPageRequestHandler */ void prependJavaScript(CharSequence javascript); + /** + * Adds a named data entry to the response, for client-side code that subscribed to it. + * <p> + * The value is delivered to the client as text, exactly as given: Wicket neither interprets, + * escapes nor evaluates it. On the client it is published on the topic + * <code>Wicket.Event.Topic.AJAX_CALL_DATA</code> (<code>'/ajax/call/data'</code>) with the + * arguments <code>(attrs, name, value)</code>, where <code>attrs</code> are the attributes of + * the Ajax call. Data entries are published in the order they were added, after the components + * have been replaced and the JavaScripts evaluated, and before the success handlers of the call + * run. + * <p> + * A subscriber that interprets the value, for example as JSON, has to treat it as data and + * never evaluate it as script or insert it as markup. + * + * @param name + * the name of the entry, used by subscribers to recognise it + * @param value + * the value to deliver + * @throws IllegalStateException + * if the response is already being written + * @since 12.0.0 + */ + void addData(String name, CharSequence value); + /** * Sets the focus in the browser to the given component. The markup id must be set. If the * component is null the focus will not be set to any component. diff --git a/wicket-core/src/main/java/org/apache/wicket/page/PartialPageUpdate.java b/wicket-core/src/main/java/org/apache/wicket/page/PartialPageUpdate.java index 4566f9217e..b186fb12c8 100644 --- a/wicket-core/src/main/java/org/apache/wicket/page/PartialPageUpdate.java +++ b/wicket-core/src/main/java/org/apache/wicket/page/PartialPageUpdate.java @@ -65,6 +65,7 @@ import org.slf4j.LoggerFactory; * <li>header-contribution - all HeaderItems which have been contributed in any{@link Component#renderHead(IHeaderResponse)}, * {@link Behavior#renderHead(Component, IHeaderResponse)} or JavaScript explicitly added via {@link #appendJavaScript(CharSequence)} * or {@link #prependJavaScript(CharSequence)}</li> + * <li>data - named values added via {@link #addData(String, CharSequence)}, for client-side subscribers</li> * </ul> */ public abstract class PartialPageUpdate @@ -96,6 +97,11 @@ public abstract class PartialPageUpdate */ protected final List<CharSequence> domReadyJavaScripts = Generics.newArrayList(); + /** + * The data entries to deliver to client-side subscribers, in the order they were added. + */ + protected final List<DataEntry> dataEntries = Generics.newArrayList(); + /** * The component instances that will be rendered/replaced. */ @@ -160,7 +166,8 @@ public abstract class PartialPageUpdate */ public boolean isEmpty() { - return prependJavaScripts.isEmpty() && appendJavaScripts.isEmpty() && domReadyJavaScripts.isEmpty() && markupIdToComponent.isEmpty(); + return prependJavaScripts.isEmpty() && appendJavaScripts.isEmpty() && domReadyJavaScripts.isEmpty() + && dataEntries.isEmpty() && markupIdToComponent.isEmpty(); } /** @@ -196,6 +203,11 @@ public abstract class PartialPageUpdate evaluationScripts.addAll(appendJavaScripts); writeEvaluations(response, evaluationScripts); + for (DataEntry entry : dataEntries) + { + writeData(response, entry.name(), entry.value()); + } + writeFooter(response, encoding); } finally { if (header != null && originalHeaderContainer != null) { @@ -475,6 +487,19 @@ public abstract class PartialPageUpdate */ protected abstract void writeEvaluation(Response response, CharSequence contents); + /** + * Writes a single data entry. + * + * @param response + * the response to write to + * @param name + * the name of the entry + * @param value + * the value of the entry + * @since 12.0.0 + */ + protected abstract void writeData(Response response, String name, CharSequence value); + @Override public boolean equals(Object o) { @@ -485,6 +510,7 @@ public abstract class PartialPageUpdate if (!appendJavaScripts.equals(that.appendJavaScripts)) return false; if (!domReadyJavaScripts.equals(that.domReadyJavaScripts)) return false; + if (!dataEntries.equals(that.dataEntries)) return false; return prependJavaScripts.equals(that.prependJavaScripts); } @@ -494,6 +520,7 @@ public abstract class PartialPageUpdate int result = prependJavaScripts.hashCode(); result = 31 * result + appendJavaScripts.hashCode(); result = 31 * result + domReadyJavaScripts.hashCode(); + result = 31 * result + dataEntries.hashCode(); return result; } @@ -533,6 +560,31 @@ public abstract class PartialPageUpdate prependJavaScripts.add(javascript); } + /** + * Adds a named data entry, delivered to client-side subscribers after the components have been + * replaced and the JavaScripts evaluated. + * + * @param name + * the name of the entry + * @param value + * the value of the entry, delivered as is + * @see org.apache.wicket.core.request.handler.IPartialPageRequestHandler#addData(String, + * CharSequence) + * @since 12.0.0 + */ + public final void addData(final String name, final CharSequence value) + { + Args.notEmpty(name, "name"); + Args.notNull(value, "value"); + + if (javascriptsFrozen) + { + throw new IllegalStateException("A partial update of the page is being rendered, data can no longer be added"); + } + + dataEntries.add(new DataEntry(name, value.toString())); + } + /** * Adds a component to be updated at the client side with its current markup * @@ -815,6 +867,19 @@ public abstract class PartialPageUpdate } } + /** + * A named data entry. + * + * @param name + * the name of the entry + * @param value + * the value of the entry + * @since 12.0.0 + */ + protected record DataEntry(String name, String value) + { + } + /** * Wrapper of a response that buffers its contents. * diff --git a/wicket-core/src/main/java/org/apache/wicket/page/XmlPartialPageUpdate.java b/wicket-core/src/main/java/org/apache/wicket/page/XmlPartialPageUpdate.java index 59ac118a6e..9b8df8cd9a 100644 --- a/wicket-core/src/main/java/org/apache/wicket/page/XmlPartialPageUpdate.java +++ b/wicket-core/src/main/java/org/apache/wicket/page/XmlPartialPageUpdate.java @@ -87,6 +87,16 @@ public class XmlPartialPageUpdate extends PartialPageUpdate writeHeaderContribution(response, "evaluate", contents); } + @Override + protected void writeData(Response response, String name, CharSequence value) + { + response.write("<data name=\""); + response.write(Strings.escapeMarkup(name)); + response.write("\"><![CDATA["); + response.write(encode(value)); + response.write("]]></data>"); + } + private void writeHeaderContribution(Response response, String elementName, CharSequence contents) { if (Strings.isEmpty(contents) == false) diff --git a/wicket-core/src/test/js/ajax.js b/wicket-core/src/test/js/ajax.js index 8a173f6358..3becd44903 100644 --- a/wicket-core/src/test/js/ajax.js +++ b/wicket-core/src/test/js/ajax.js @@ -130,6 +130,34 @@ Wicket.Event.add(window, 'domready', function() { execute(attrs, assert); }); + test('processData publishes data entries in order, after evaluations.', assert => { + const done = assert.async(); + assert.expect(5); + + Wicket.dataTestEvaluated = false; + const received = []; + + const attrs = { + u: 'data/ajax/dataResponse.xml' + }; + + Wicket.Event.subscribe(Wicket.Event.Topic.AJAX_CALL_DATA, function (jqEvent, callAttrs, name, value) { + assert.ok(Wicket.dataTestEvaluated, 'Data is published after the evaluations'); + assert.equal(callAttrs.u, attrs.u, 'Data is published with the attributes of the call'); + received.push([name, value]); + }); + + attrs.sh = [ + function () { + assert.deepEqual(received, [['first', '{"value":"a]]>b"}'], ['second', 'two']], + 'All data is published, in order, before the success handlers'); + done(); + } + ]; + + execute(attrs, assert, done); + }); + test('processComponent, normal case.', assert => { const done = assert.async(); assert.expect(2); diff --git a/wicket-core/src/test/js/data/ajax/dataResponse.xml b/wicket-core/src/test/js/data/ajax/dataResponse.xml new file mode 100644 index 0000000000..f016cc89b3 --- /dev/null +++ b/wicket-core/src/test/js/data/ajax/dataResponse.xml @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<ajax-response> +<data name="first"><![CDATA[{"value":"a]]]]><![CDATA[>b"}]]></data> +<evaluate><![CDATA[ +<head xmlns:wicket="http://wicket.apache.org"> +<script type="text/javascript"> +/*<![CDATA[*/ +Wicket.dataTestEvaluated = true; +/*]]]]><![CDATA[>*/ +</script> +</head> +]]></evaluate> +<data name="second"><![CDATA[two]]></data> +</ajax-response> diff --git a/wicket-user-guide/src/main/asciidoc/ajax/ajax_6.adoc b/wicket-user-guide/src/main/asciidoc/ajax/ajax_6.adoc index 1137ce6ba3..788468706e 100644 --- a/wicket-user-guide/src/main/asciidoc/ajax/ajax_6.adoc +++ b/wicket-user-guide/src/main/asciidoc/ajax/ajax_6.adoc @@ -168,6 +168,7 @@ Global AJAX call events are handled with JavaScript. We can register a callback * '/ajax/call/failure': called if the AJAX call has returned with a failure. * '/ajax/call/complete': called when the AJAX call has completed. * '/ajax/call/done': called when the AJAX call is done. +* '/ajax/call/data': called for every data entry added on the server with _addData(name, value)_ of _AjaxRequestTarget_, after the components have been replaced and the JavaScript evaluated, and before the success handlers run. Its callback receives jqEvent, attrs, name and value. Wicket delivers the value as text, without interpreting it, so the subscriber must treat it as data and never evaluate it. * '/dom/node/removing': called when a component is about to be removed via AJAX. This happens when component markup is updated via AJAX (i.e. the component itself or one of its containers has been added to _AjaxRequestTarget_) * '/dom/node/added': called when a component has been added via AJAX. Just like '/dom/node/removing', this event is triggered when a component is added to _AjaxRequestTarget_.
