Struts 2 – Interceptor重置响应JSON对象

我在我的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对象作为响应。 请帮我解决这个问题。

您的代码中存在多个错误。

  • 响应是HttpServletResponse ,您不应该将该名称赋予JSONObject。
  • 拦截器不是THREAD-SAFE,这意味着你应该在方法中定义JSONObject,以防止多个用户同时更新它,一个在另一个上面
  • 您应该使用jSON 插件文档中描述的 statusCode或errorCode ,将其配置为您要返回的错误结果:

使用statusCode设置响应的状态:

  304  

并且errorCode发送错误(服务器可能最终向客户端发送不是序列化JSON的东西):

   404  

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