Interceptor in SSM: Function and Implementation Principle

Interceptor in SSM: Function and Implementation Principle

Interceptor is an important component in the Spring framework, and also plays a key role in frameworks such as Spring + Spring MVC + MyBatis (SSM). This article will delve into the role and function of interceptors in SSM, and how to implement a custom interceptor.

Insert image description here

What is an interceptor?

An interceptor is an application design pattern that is used to intercept, intercept, or capture certain events or behaviors and then perform a predefined action without intervening with the original request. In SSM, interceptors are mainly used to process HTTP requests and responses, performing specific operations before the request reaches the controller and before the response is returned to the client.

Interceptors are part of the Spring framework, which allow developers to insert their own logic at different stages of request processing, such as permission verification, logging, performance monitoring, etc. Interceptors are typically most widely used in Spring MVC, but can also be used in Spring + MyBatis or other frameworks.

The role of interceptors

Interceptors have several important roles in SSM:

1. Permission verification

Interceptors can be used to verify whether a user has permission to access a specific page or perform a certain action. For example, an interceptor for an online store could check whether the user is logged in and has permission to purchase items.

public class AuthInterceptor implements HandlerInterceptor {
    
    

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
    
    
        // 检查用户是否登录,如果未登录,跳转到登录页面
        if (!isUserLoggedIn(request)) {
    
    
            response.sendRedirect("/login");
            return false;
        }
        // 检查用户是否有权限访问该页面或执行该操作
        if (!hasPermission(request)) {
    
    
            response.sendRedirect("/unauthorized");
            return false;
        }
        return true;
    }

    // 省略实现细节
}

2. Logging

Interceptors can be used to log request and response details for debugging, performance analysis, or security auditing. Through interceptors, we can capture request parameters, execution time, response status code and other information.

public class LoggingInterceptor implements HandlerInterceptor {
    
    

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    
    
        // 记录请求信息,包括请求路径、请求参数、执行时间等
        logRequestInfo(request);
        // 记录响应信息,包括响应状态码、响应内容等
        logResponseInfo(response);
    }

    // 省略实现细节
}

3. Performance monitoring

Interceptors can be used to monitor application performance, including request processing time, resource consumption, etc. This helps identify performance bottlenecks and optimize them.

public class PerformanceInterceptor implements HandlerInterceptor {
    
    

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
    
    
        request.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
    
    
        long startTime = (long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        // 记录请求处理时间
        logPerformance(request, executionTime);
    }

    // 省略实现细节
}

Implement a custom interceptor

To implement a custom interceptor in SSM, you generally need to complete the following steps:

  1. Create a class that implements HandlerInterceptorthe interface.
  2. Implement corresponding logic in the interceptor, such as permission verification, logging, or performance monitoring.
  3. Configure the interceptor and tell Spring on which request paths to apply the interceptor.

Here's an example showing how to create a simple interceptor that logs the processing time of a request:

public class PerformanceInterceptor implements HandlerInterceptor {
    
    

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
    
    
        request.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
    
    
        long startTime = (long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        // 记录请求处理时间
        logPerformance(request, executionTime);
    }

    private void logPerformance(HttpServletRequest request, long executionTime) {
    
    
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        System.out.println("Request URI: " + requestURI);
        System.out.println("HTTP Method: " + method);
        System.out.println("Execution Time: " + executionTime + "ms");
    }
}

Configure the application of interceptor in Spring MVC:

<!-- 配置拦截器 -->
<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**" />
        <bean class="com.example.PerformanceInterceptor" />
    </mvc:interceptor>
</mvc:interceptors>

The above configuration will PerformanceInterceptorbe applied to all request paths.

Summarize

Interceptors are important components in the SSM framework and are used to perform various logical operations during processing requests and responses. Its functions include permission verification, logging, performance monitoring, etc. By implementing a custom interceptor, developers can extend its functionality according to the needs of the project to improve the maintainability, security, and performance of the application. By understanding the principles and usage of interceptors, you can better apply it to meet the project's needs

need.

Guess you like

Origin blog.csdn.net/u013749113/article/details/133487800