我们有时候需要根据请求类型来判断返回视图名称还是JSON数据,这里记录一个判断Ajax的工具类方便日后好找

通过传入Request对象获取头信息,根据头信息判断是否属于Ajax请求

public class AjaxUtil {
    /**
     * 用来判断请求属不属于Ajax请求
     * @param req http请求
     * @return true表示ajax请求
     */
    public static boolean isAjax(HttpServletRequest req){
        String accept = req.getHeader("Accept");
        String with = req.getHeader("X-Requested-With");
        return ( accept != null && accept.contains("application/json") )
                || ( with != null && with.contains("XMLHttpRequest") );
    }
}

相关文章:

  • 2022-01-07
  • 2022-12-23
  • 2021-09-07
  • 2022-12-23
  • 2021-12-04
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-15
  • 2021-05-27
  • 2022-12-23
相关资源
相似解决方案