问题描述
我想对 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();