10

I am using JSF framework in my application. I need to run a specific script before the render response phase in my Phase Listener class.

Condition for running this script is that, if the request triggered is a Ajax request i need to run the script, if the request triggered is a Http request i should not run that script.

Can anyone please help me to differentiate the requests recieved.?

jmj
  • 237,923
  • 42
  • 401
  • 438
R K
  • 1,283
  • 1
  • 14
  • 41

3 Answers3

18

Ajax requests have usually a X-Requested-With: XMLHttpRequest request header. In JSF, you can obtain the request headers by ExternalContext#getRequestHeaderMap().

ExternalContext externalContext = facesContext.getExternalContext();
Map<String, String> headers = externalContext.getRequestHeaderMap();
boolean ajax = "XMLHttpRequest".equals(headers.get("X-Requested-With"));
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • if you are using RF then `request.getParameter("AJAXREQUEST")==null` will also work – jmj Feb 03 '11 at 12:10
  • Yes, you can also hook on implementation/library-specific parameters/attributes, but that tight-couples your code to specific implementations/libraries. – BalusC Feb 03 '11 at 12:11
  • 1
    Where do ajax requests originate? JSF? JS library? Homegrown? Anyway, just determine the request headers to see if there's a viable key/value pair which differs between normal and ajax requests. Do `System.out.println(headers);` to see them. – BalusC Feb 03 '11 at 14:16
4

Ajax requests set a server variable X-Requested-With to XMLHttpRequest. You can use that information to differentiate between ajax and normal requests.

Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185
3
private boolean isAjaxRequest() {
  PartialViewContext partialViewContext = FacesContext.getCurrentInstance().getPartialViewContext();
  return null != partialViewContext && partialViewContext.isAjaxRequest();
}
eirirlar
  • 814
  • 6
  • 24