我在我的 Web 应用程序中使用 Struts 2.我编写代码将用户会话检查到拦截器中,但是当我返回 net.sf.json.JSONObject
作为响应时,它会重置响应对象并将 null 设置为对象.请检查我的代码.
导入 net.sf.json.JSONObject;导入 com.opensymphony.xwork2.interceptor.Interceptor;公共类 AuthorizationInterceptor 实现拦截器 {JSONObject 响应 = 新 JSONObject();公共字符串拦截(ActionInvocation 调用){尝试 {映射会话 = invocation.getInvocationContext().getSession();if (session.get("userId") == null) {response.put("errorCode", "SESSION_OUT");返回 ActionSupport.ERROR;} 别的 {System.out.println("找到会话");对象动作 = invocation.getAction();返回调用.invoke();}} 捕捉(异常 e){返回 ActionSupport.ERROR;}}公共 JSONObject getResponse() {返回响应;}公共无效 setResponse(JSONObject 响应){this.response = 响应;}
}
如何获取 JSON 对象作为拦截器的响应.请帮我解决这个问题.
您的代码中有多个错误.
使用 statusCode 设置响应的状态:
<result name="error" type="json"><param name="statusCode">304</param></结果>
<块引用>
和 errorCode 发送错误(服务器可能最终向客户端发送不是序列化 JSON 的内容):
<result name="error" type="json"><param name="errorCode">404</param></结果>
然后在 AJAX 回调函数中读取它的客户端.
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.
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.
这篇关于Struts 2 - 拦截器重置响应 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!