Distinguish whether the request is an ajax request or a normal request

There are thousands of ways, the most important thing that suits you.

ajax request: returns json

Normal request: a page is returned

1. Guide package

            <!-- 引入 Servlet 容器中相关依赖 -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
                <scope>provided</scope>
            </dependency>

2. View the ajax request from the browser, the unique data of the request header is as follows:

3. Write a static tool class to determine whether it is an ajax request 

public class CrowdUtil {
    /**
     * 判断当前请求是否是ajax请求
     * @param request 请求对象
     * @return 返回true:是ajax请求
     */
    public static boolean judgeRequestType(HttpServletRequest request){
        //1.获取请求消息投
        String acceptHeader=request.getHeader("Accept");
        String xRequestedHeader=request.getHeader("X-Requested-With");
        //2.判断,返回true:是ajax请求
        return  ((acceptHeader!=null&&acceptHeader.contains("application/json"))||(xRequestedHeader!=null&&xRequestedHeader.equals("XMLHttpRequest")));

    }
}

4. Call method

 boolean judgeRequestType = CrowdUtil.judgeRequestType(request);

As shown below:

 

Guess you like

Origin blog.csdn.net/zaq977684/article/details/121974853