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