Struts 2 - Interceptor重置响应JSON对象 [英] Struts 2 - Interceptor reset the response JSON Object
问题描述
我在我的网络应用程序中使用Struts 2。我编写代码来检查用户会话到拦截器但是当我返回 net.sf.json.JSONObject
作为响应时,它重置响应对象并将null设置为对象。
请检查我的代码。
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;
}
}
如何从拦截器获取JSON对象作为响应。
请帮我解决这个问题。
How can I get the JSON Object as response from interceptor. Please help me to resolve this issue.
推荐答案
有多个错误你的代码。
- 回应是 HttpServletResponse ,您不应该将该名称赋予JSONObject。
- 拦截器不是线程安全的,这意味着你应该在方法中定义JSONObject,以防止多个用户同时更新它,一个在另一个上面
- 你应该使用statusCode或errorCode 如JSON插件文档中所述,将其配置为您要返回的错误结果:
- 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:
使用statusCode设置响应的状态:
Use statusCode to set the status of the response:
<result name="error" type="json">
<param name="statusCode">304</param>
</result>
并且errorCode发送错误(服务器可能最终发送一些东西到不是序列化JSON的客户端:
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>
然后在AJAX回调函数的客户端读取它。
and then read it client-side in the AJAX callback function.
这篇关于Struts 2 - Interceptor重置响应JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!