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.
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