Ajax请求与传统请求的不同

写项目时,我需要获取请求头,遇到这个问题就是传统请求和ajax请求不同:ajax请求会多一个X-Requested-With请求头信息

  1、传统同步请求参数

    

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
Cache-Control: max-age=0
Connection: keep-alive
Cookie: Idea-3288ddda=a0d3088e-e55f-4122-8422-508a09570c44; JSESSIONID=D76E50B0F0BF1D45FAEA6D48BBFA8E31
Host: localhost:8080
If-Modified-Since: Sat, 09 Mar 2019 12:25:12 GMT
If-None-Match: W/"4301-1552134312000"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36

 

  2、Ajax 异步请求方式

Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
Connection: keep-alive
Cookie: Idea-3288ddda=a0d3088e-e55f-4122-8422-508a09570c44; JSESSIONID=D76E50B0F0BF1D45FAEA6D48BBFA8E31
Host: localhost:8080
Referer: http://localhost:8080/index.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36
X-Requested-With: XMLHttpRequest

     可以看到 Ajax 请求多了个 x-requested-with 的头部信息,可以用它判断请求的方式:

public void doXXX(HttpServletRequest request, HttpServletResponse response){  
       String uri = request.getRequestURI();  
       if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
               System.out.println(uri+":Ajax异步请求");
            }else {
               System.out.println(uri+":传统同步请求");
            }  
}

 

你可能感兴趣的:(Ajax)