开发者

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

开发者 https://www.devze.com 2023-01-30 05:33 出处:网络
I need to set a custom HTTP header to all responses from my Wicket application. I\'m currently doing it in a custom RequestCycle, where getWebResponse() is开发者_如何学编程 overridden along these line

I need to set a custom HTTP header to all responses from my Wicket application. I'm currently doing it in a custom RequestCycle, where getWebResponse() is开发者_如何学编程 overridden along these lines:

@Override
public WebResponse getWebResponse() {
    WebResponse response = super.getWebResponse();
    response.setHeader("X-custom", "..." );
    return response;
}

This has worked great, until now that I've switched to using AjaxCheckBox (something like this) instead of normal CheckBox for certain configuration options.

My question is, is there an easy way to include my custom header also in Wicket's Ajax responses?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号