JAVA如何判断一个请求是否为Ajax请求呢?
下文笔者讲述java代码检测请求是否为"Ajax"请求的方法及示例分享,如下所示
通过头文件的方式 即可判断是否为Ajax请求例:检测是否为Ajax请求的示例
/** * 是否是Ajax异步请求 * * @param request */ public static boolean isAjaxRequest(HttpServletRequest request) { String accept = request.getHeader("accept"); if (accept != null && accept.indexOf("application/json") != -1) { return true; } String xRequestedWith = request.getHeader("X-Requested-With"); if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) { return true; } String uri = request.getRequestURI(); if (isContainStrs(uri, ".json", ".xml")) { return true; } String ajax = request.getParameter("__ajax"); if (isContainStrs(ajax, "json", "xml")) { return true; } return false; } public static boolean isContainStrs(String str, String... strs) { if (str != null && strs != null) { for (String s : strs) { if (str.equalsIgnoreCase(trim(s))) { return true; } } } return false; } public static String trim(String str) { return (str == null ? "" : str.trim()); }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。