How to determine if a request is Ajax or Normal?

I want to handle errors differently for AJAX requests and regular requests.

How to determine if an AJAX request or not in Struts2 actions?

+6
source share
2 answers

You should check if the X-Requested-With request header is present and is equal to XMLHttpRequest .

Note that not all AJAX requests have this header; for example, Struts2 Dojo requests do not send it; if you instead generate AJAX calls using Struts2-jQuery (or with any other new AJAX framework), it is.

You can check if this is present with the Firebug Net module ... for example, when you vote for a stack overflow;)

To verify this with the Struts2 Action , you need to implement the ServletRequestAware interface, then get the Request and check if this particular header exists, for example:

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

Please note that you can also receive a request through an ActionContext without using the ServletRequestAware interface, but this is not recommended:

 HttpServletRequest request = ServletActionContext.getRequest(); 
+14
source

Another option I use is to add the ajax = true parameter to all lines of the Ajax URL and check in my action using the isAjax () method.

+4
source

All Articles