JAVA判断是否是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());
    }

 

posted @ 2021-12-13 14:42  yvioo  阅读(456)  评论(0编辑  收藏  举报