【问题标题】:Struts 2 - Interceptor reset the response JSON ObjectStruts 2 - 拦截器重置响应 JSON 对象
【发布时间】:2013-06-18 13:39:45
【问题描述】:

我在我的 Web 应用程序中使用 Struts 2。我编写代码将用户会话检查到拦截器中,但是当我返回 net.sf.json.JSONObject 作为响应时,它重置响应对象并将 null 设置为对象。 请检查我的代码。

import net.sf.json.JSONObject;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class AuthorizationInterceptor implements Interceptor {

JSONObject response = new JSONObject();

public String intercept(ActionInvocation invocation) {
 try { 
      Map session = invocation.getInvocationContext().getSession();
        if (session.get("userId") == null) {
           response.put("errorCode", "SESSION_OUT");                
            return ActionSupport.ERROR;
        } else {
            System.out.println("Session found");
            Object action = invocation.getAction();
            return invocation.invoke();
        }
    } catch (Exception e) {
        return ActionSupport.ERROR;
    }
}

public JSONObject getResponse() {
    return response;
}

public void setResponse(JSONObject response) {
    this.response = response;
}

}

如何获取 JSON 对象作为拦截器的响应。 请帮我解决这个问题。

【问题讨论】:

  • 如果你知道它是什么,直接调用它。

标签: java json struts2 interceptor


【解决方案1】:

您的代码中有多个错误。

  • 响应为 HttpServletResponse,您不应将该名称指定给 JSONObject。
  • 拦截器不是线程安全的,这意味着您应该在方法内定义 JSONObject,以防止多个用户一个接一个地同时更新它
  • 您应该使用 statusCode 或 errorCode as described in the JSON plugin documentation,将其配置为您返回的错误结果:

使用 statusCode 设置响应的状态:

<result name="error" type="json">
  <param name="statusCode">304</param>
</result>

和 errorCode 发送错误(服务器可能最终向客户端发送不是序列化 JSON 的内容):

 <result name="error" type="json">
  <param name="errorCode">404</param>
</result>

然后在 AJAX 回调函数中读取它的客户端。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2011-10-25
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多