Struts 2 - Interceptor reset the response JSON Object

感情迁移 提交于 2019-11-28 13:55:09

问题


I am using Struts 2 in my web application. I write code to check user session into interceptor but while I am returning net.sf.json.JSONObject as response, its reset the response object and set null to the object. Please check my code.

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

}

How can I get the JSON Object as response from interceptor. Please help me to resolve this issue.


回答1:


There are mutliple errors in your code.

  • Response is HttpServletResponse, you should not give that name to a JSONObject.
  • Interceptors are NOT THREAD-SAFE, that means that you should define the JSONObject inside the method, to prevent multiple users to update it concurrently, one over the other
  • You should use statusCode or errorCode as described in the JSON plugin documentation, by configuring it as the Error result you are returning:

Use statusCode to set the status of the response:

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

And errorCode to send an error(the server might end up sending something to the client which is not the serialized JSON):

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

and then read it client-side in the AJAX callback function.



来源:https://stackoverflow.com/questions/17234976/struts-2-interceptor-reset-the-response-json-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!