zoukankan      html  css  js  c++  java
  • SpringBoot学习笔记:自定义拦截器

    SpringBoot学习笔记:自定义拦截器

    快速开始 

      拦截器类似于过滤器,但是拦截器提供更精细的的控制能力,它可以在一个请求过程中的两个节点进行拦截:

    • 在请求发送到Controller之前
    • 在响应发送到Client之前

      例如,你可以使用拦截器在将请求发送到控制器之前添加请求头,并在将响应发送到客户端之前添加响应标头。

    创建拦截器

      创建一个拦截器,需要实现HandlerInterceptor接口,他有三个方法来完成拦截

    • preHandle(): 用于在将请求发送到控制器之前执行操作。此方法应返回true以将响应返回给客户端

    • postHandle() :用于在将响应结果发送到客户端之前执行操作。

    • afterCompletion() :用于在请求响应全部结束后执行之后的操作。

      一个自定义的拦截器代码如下:

    @Component
    public class ProductServiceInterceptor implements HandlerInterceptor {
       @Override
       public boolean preHandle(
          HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          
          return true;
       }
       @Override
       public void postHandle(
          HttpServletRequest request, HttpServletResponse response, Object handler, 
          ModelAndView modelAndView) throws Exception {}
       
       @Override
       public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
          Object handler, Exception exception) throws Exception {}
    }

    注册拦截器

      拦截器完成后,必须使用WebMvcConfigurerAdapter向InterceptorRegistry注册此Interceptor,如下所示

    @Component
    public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter {
       @Autowired
       ProductServiceInterceptor productServiceInterceptor;
    
       @Override
       public void addInterceptors(InterceptorRegistry registry) {
          registry.addInterceptor(productServiceInterceptor);
       }
    }
    

      

  • 相关阅读:
    Mac下发布Unity3d中Android平台下出现“android (invokation failed)”的错误
    图片切换特过渡效果
    文件下载
    ASP.NET前台绑定后台变量方法总结
    C# aspx 数据绑定集中 Bind Eval DataBinder.Eval
    MVC 3 Excel文件下载
    ASP.NET中Get和Post的用法 Request.QueryString,Request.Form,Request.Params的区别
    删除掉前一天文件夹里面的文件
    友情链接
    博客园管理记录
  • 原文地址:https://www.cnblogs.com/MrSaver/p/11201867.html
Copyright © 2011-2022 走看看