Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC detect ajax request

How to detect an ajax request in the best possible way?

I'm currently using this in my controller:

private boolean isAjax(HttpServletRequest request){
    String header = request.getHeader("x-requested-with");
    if(header != null && header.equals("XMLHttpRequest"))
        return true;
    else
        return false;
}

But I don't like this way, I think there should have a better solution with Spring.

like image 633
Fernando Gomes Avatar asked May 26 '15 14:05

Fernando Gomes


1 Answers

That is the only "generic" way to detect an Ajax request.

But keep in mind: that's not failproof, it is just a best effort attempt, it is possible to make an Ajax request without sending the X-Requested-With headers.

jQuery usually includes that header. Maybe another lib doesn't. The protocol certainly doesn't consider that header mandatory.


Just a note: Your code is perfectly valid, though you could write it a bit simpler:

private boolean isAjax(HttpServletRequest request) {
    String requestedWithHeader = request.getHeader("X-Requested-With");
    return "XMLHttpRequest".equals(requestedWithHeader);
}
like image 116
acdcjunior Avatar answered Nov 08 '22 23:11

acdcjunior