如何在Wicket的Ajax响应中设置自定义HTTP响应标头?

问题描述:

我需要为Wicket应用程序的所有响应设置自定义HTTP标头.我目前正在自定义RequestCycle中进行操作,其中getWebResponse()沿这些行被覆盖:

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;
}

这一直很好,直到现在我切换到使用AjaxCheckBox(

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

我的问题是,是否有一种简单的方法可以将我的自定义标头还要包含在Wicket的Ajax响应中?

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

我找到了一种方法.最后,实际上一点也不难.当使用调试器运行某些请求时,我注意到 onEndRequest() 也会被Ajax请求调用.

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.

在我们的自定义RequestCycle实现中,onEndRequest()方法已被其他目的(事务提交)所覆盖,因此我刚刚移动了从getWebResponse()设置标头的代码.

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", "..." );
    // ...
}

也许这里唯一不明显的事情是我需要将response强制转换为响应),以便可以调用setHeader().

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!