java 如何判断一个请求是Ajax还是Normal?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14621539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:51:47  来源:igfitidea点击:

How to determine whether a request is Ajax or Normal?

javaajaxstruts2http-headersstruts-action

提问by Amol Ghotankar

I want to handle errors differently for AJAX requests vs normal requests.

我想以不同的方式处理 AJAX 请求和普通请求的错误。

How do I identify whether a request is AJAX or not in Struts2 actions ?

如何在 Struts2 操作中识别请求是否为 AJAX?

回答by Andrea Ligios

You should check if the Request Header X-Requested-Withis present and equals to XMLHttpRequest.

您应该检查请求标头X-Requested-With是否存在并且等于XMLHttpRequest

Note that not all the AJAX requests have this header, for example Struts2 Dojorequests don't send it; if you instead are generating AJAX calls with Struts2-jQuery(or with any other new AJAX framework), it is there.

请注意,并非所有 AJAX 请求都有此标头,例如Struts2 Dojo请求不会发送它;如果您使用Struts2-jQuery(或任何其他新的 AJAX 框架)生成 AJAX 调用,它就在那里。

You can check if it's present by using Firebug's Net module... for example, when you vote on Stack Overflow ;)

您可以使用Firebug's Net module...检查它是否存在,例如,当您对 Stack Overflow 进行投票时;)

To check it from within a Struts2 Action, you need to implement the ServletRequestAwareinterface, then get the Requestand check if that particular header is there like this:

要从 a 中检查它Struts2 Action,您需要实现该ServletRequestAware接口,然后获取Request并检查该特定标头是否存在,如下所示:

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;
   }  
}

Note that you can obtain the request via ActionContext too, without implementing the ServletRequestAware interface, but it is not the recommended way:

请注意,您也可以通过 ActionContext 获取请求,而无需实现 ServletRequestAware 接口,但这不是推荐的方式:

HttpServletRequest request = ServletActionContext.getRequest();

回答by user497087

The other alternative, which I use is to add the parameter ajax=true to all Ajax url strings and test in my action with an isAjax() method.

我使用的另一种替代方法是将参数 ajax=true 添加到所有 Ajax url 字符串,并使用 isAjax() 方法在我的操作中进行测试。