How to set custom HTTP response header in Wicket's Ajax responses?

☆樱花仙子☆ 提交于 2019-12-06 14:04:01
Jonik

I found a way. It actually wasn't hard at all, in the end. When running through some requests with my debugger, I noticed that onEndRequest() does get called for Ajax requests too.

The onEndRequest() method was already overriden in our custom RequestCycle implementation for other purposes (transaction commit), so I just moved the code that sets the header there from getWebResponse().

@Override
protected void onEndRequest() {
    super.onEndRequest();
    ((WebResponse) response).setHeader("X-custom", "..." );
    // ...
}

Perhaps the only non-obvious thing here was that I needed to cast response into WebResponse (when the field's type is Response) to be able to call setHeader().

This could have been done in a normal Java EE filter too, by setting the header after chain.doFilter() call (see my second comment on the question). I didn't choose that because 1) it wasn't clear to me how to wire up data access there and 2) I don't want extra moving parts if I can avoid it. We already use our RequestCycle subclass for HTTP header related things and this fits in nicely. In fact, this change simplified that class, as there's no reason to override getWebResponse() anymore!

Under the hood, Wicket still uses the standard Java HTML stack. So instead of overriding existing methods, just implement a Filter and register it in your web.xml. With the correct URL pattern, it will apply to all requests, no matter who handles them.

Looking at the implementation of AjaxRequestTarget

[...]

/**
 * @see org.apache.wicket.IRequestTarget#respond(org.apache.wicket.RequestCycle)
 */
public final void respond(final RequestCycle requestCycle)
{
    final WebResponse response = (WebResponse)requestCycle.getResponse();

    if (markupIdToComponent.values().contains(page))

[...]

the Wicket solution would be to override RequestCycle.getResponse() instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!