How to determine whether a request is Ajax or Normal?

落花浮王杯 提交于 2019-12-01 01:32:21

问题


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

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


回答1:


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

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.

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

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

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();



回答2:


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.



来源:https://stackoverflow.com/questions/14621539/how-to-determine-whether-a-request-is-ajax-or-normal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!