gpt4 book ai didi

java - Struts 2 拦截器响应 header 未设置

转载 作者:行者123 更新时间:2023-12-02 10:08:50 26 4
gpt4 key购买 nike

Struts 2.5.18

我在 Struts 2 拦截器中设置 header 时遇到问题,并且客户端未收到返回的 header 。我在另一个 Struts 2 项目中使用完全相同的拦截器,没有出现任何问题。

我确实偶然发现了这篇文章How can I configure HTTP Response Headers in a Struts2 Interceptor?它有同样的问题并通过切换从 ServletActionContext.getResponse() 获取响应来解决它从调用上下文获取它 invocation.getInvocationContext().get(StrutsStatics.HTTP_RESPONSE)

这最终导致了相同的结果,即 header 仍未发送回浏览器。我正在使用开发人员工具来监视响应 header ,但它不存在。

此外,我在响应中调用 setHeader() 后立即添加了一条调试消息,以使用 containsHeader() 查看响应是否包含新 header 。 containsHeader() 会导致 FALSE,就好像 setHeader 根本不起作用一样。

有人对响应对象可能发生的情况有任何建议吗? Intercept() 方法如下

public String intercept(ActionInvocation invocation) throws Exception {
String result = invocation.invoke();
Boolean hasValidationErrors = Boolean.FALSE;
Object action = invocation.getAction();
if(action instanceof ValidationAware) {
ValidationAware validationAware = (ValidationAware) action;
hasValidationErrors = validationAware.hasErrors();

}

HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(StrutsStatics.HTTP_RESPONSE);
response.setHeader(VALIDATION_FLAG_HEADER_NAME, String.valueOf(hasValidationErrors));

if (log.isDebugEnabled()) log.debug("Does response contain new header? " + response.containsHeader(VALIDATION_FLAG_HEADER_NAME));

return result;
}

更新:应用戴夫修复后的工作代码

  public String intercept(ActionInvocation invocation) throws Exception {

invocation.addPreResultListener((actionInvocation, resultCode) -> {
// perform operation necessary before Result execution
Boolean hasValidationErrors = Boolean.FALSE;
Object action = invocation.getAction();
if(action instanceof ValidationAware) {
ValidationAware validationAware = (ValidationAware) action;
hasValidationErrors = validationAware.hasErrors();

}

HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(StrutsStatics.HTTP_RESPONSE);
response.setHeader(VALIDATION_FLAG_HEADER_NAME, String.valueOf(hasValidationErrors));

if (log.isDebugEnabled()) log.debug("Does response contain new header? " + response.containsHeader(VALIDATION_FLAG_HEADER_NAME));

});

return invocation.invoke();
}

最佳答案

您在调用 invoke 之后设置 header ,此时响应已呈现。

来自https://struts.apache.org/core-developers/writing-interceptors.html :

Keep in mind that invoke will return after the result has been called (eg. after you JSP has been rendered), making it perfect for things like open-session-in-view patterns. If you want to do something before the result gets called, you should implement a PreResultListener.

在调用invoke之前设置 header ,或实现PreResultListener

关于java - Struts 2 拦截器响应 header 未设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55144810/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com