52

Spring MVC拦截器学习

 4 years ago
source link: https://www.tuicool.com/articles/aI7bmqU
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

1 介绍

Spring Web MVC是基于Servlet API构建的原始Web框架。

2 拦截器

2.1 定义

springmvc框架的一种拦截机制

2.2 使用

2.2.1 两步走

  1. 实现HandlerInterceptor接口
  2. 注册(xml或者注解 )

2.2.2 HandlerInterceptor接口

rem2mif.png!web

  1. 实现HandlerInterceptor接口
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InterceptorTest implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true; // 只有返回true才会继续向下执行,返回false取消当前请求
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
  1. 注册
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 注册拦截器(扫描到拦截器)
 */
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new InterceptorTest()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}
  1. 使用场景

拦截器可以在请求前后进行数据拦截,类似门岗,门岗一般都有检查身份功能,对于拦截器来说,拦截器有权限校验功能,把握请求是否可以通过,可以在里面进行token检验或者其他。

性能检测。可以在请求前后进行时间计算,检测接口性能。

日记记录。拦截请求数据,记录请求参数。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK