How to determine whether a request is Ajax or Normal?(如何判断一个请求是Ajax还是Normal?)
问题描述
我想对 AJAX 请求和普通请求以不同的方式处理错误.
I want to handle errors differently for AJAX requests vs normal requests.
如何在 Struts2 操作中识别请求是否为 AJAX?
How do I identify whether a request is AJAX or not in Struts2 actions ?
推荐答案
您应该检查请求标头 X-Requested-With
是否存在并且等于 XMLHttpRequest
.
You should check if the Request Header X-Requested-With
is present and equals to XMLHttpRequest
.
请注意,并非所有 AJAX 请求都有此标头,例如 Struts2 Dojo
请求不发送它;如果您使用 Struts2-jQuery
(或任何其他新的 AJAX 框架)生成 AJAX 调用,它就在那里.
Note that not all the AJAX requests have this header, for example Struts2 Dojo
requests don't send it; if you instead are generating AJAX calls with Struts2-jQuery
(or with any other new AJAX framework), it is there.
您可以使用 Firebug 的 Net 模块
来检查它是否存在...例如,当您在 Stack Overflow 上投票时;)
You can check if it's present by using Firebug's Net module
... for example, when you vote on Stack Overflow ;)
要从 Struts2 Action
中检查它,您需要实现 ServletRequestAware
接口,然后获取 Request
并检查该特定标题是这样的:
To check it from within a Struts2 Action
, you need to implement the ServletRequestAware
interface, then get the Request
and check if that particular header is there like this:
public class MyAction extends ActionSupport implements ServletRequestAware {
private HttpServletRequest request;
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletRequest getRequest() {
return this.request;
}
public String execute() throws Exception{
boolean ajax = "XMLHttpRequest".equals(
getRequest().getHeader("X-Requested-With"));
if (ajax)
log.debug("This is an AJAX request");
else
log.debug("This is an ordinary request");
return SUCCESS;
}
}
注意,你也可以通过 ActionContext 获取请求,不需要实现 ServletRequestAware 接口,但不是推荐的方式:
Note that you can obtain the request via ActionContext too, without implementing the ServletRequestAware interface, but it is not the recommended way:
HttpServletRequest request = ServletActionContext.getRequest();
这篇关于如何判断一个请求是Ajax还是Normal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何判断一个请求是Ajax还是Normal?
基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01