2013-06-21 51 views
-1

我在我的web應用程序中使用Struts 2。我編寫代碼來檢查用戶會話到攔截器中,但是當我作爲響應返回net.sf.json.JSONObject時,它將重置響應對象並將null設置爲對象。 請檢查我的代碼。Struts 2 - 攔截器重置響應JSON對象

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對象從攔截響應。 請幫我解決這個問題。

+0

如果您知道它是什麼,請直接調用該操作。 –

回答

2

代碼中存在多重錯誤。

  • 響應是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回調函數。