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 ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You should check if the Request Header
X-Requested-Withis present and equals toXMLHttpRequest.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 withStruts2-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 theServletRequestAwareinterface, then get theRequestand check if that particular header is there like this:Note that you can obtain the request via ActionContext too, without implementing the ServletRequestAware interface, but it is not the recommended way: