SpringBoot之拦截器优雅注入请求根目录到request中

  发布日期:   2019-01-17
  最新修改:   2020-10-25
  阅读次数:   881 次


  • 在上一章节中我们讲解了Spring Boot中拦截器的基本使用步骤

  • 在编写网页时我们难免需要用到请求的项目跟目录如http://localhost:8080,如果你不想使用相对路径的情况下

  • 本次我们就通过拦截器为所需要的请求默认带上该变量,

  • OK,直接上代码:

  • 首先我们实现一个PathInterceptor 拦截器

      @Component
      public class PathInterceptor implements HandlerInterceptor {
         private void printMsg(String msg) {
            System.out.println("[PathInterceptor] " +msg);
    
         }
         @Override
         public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            printMsg("preHandle");
            request.setAttribute("host", Utils.getHostPath(request));
            return true;
         }
         @Override
         public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
            printMsg("postHandle");
         }
    
         @Override
         public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
            Object handler, Exception exception) throws Exception {
            printMsg("afterCompletion");
    
         }
      }
  • 拦截器写好了,此时就是要将我们的拦截器与Spring关联上并告知 如何调用了

  • 通过实现一个WebMvcConfigurer,然后通过addInterceptors方法参数中的注册器注册拦截器

         @Component
        public class ProductServiceInterceptorAppConfig implements WebMvcConfigurer {
           @Autowired
           PathInterceptor pathInterceptor;
    
           @Autowired
           AdminLoginInterceptor adminLoginInterceptor;
    
           @Override
           public void addInterceptors(InterceptorRegistry registry) {
              registry.addInterceptor(pathInterceptor).addPathPatterns("/**"); //拦截所有目录
         }
      }
  • 工具类如下:

     public class Utils {
    
         public static String getHostPath(HttpServletRequest request) {
             String host = "";
             host = request.getScheme() +"://" + request.getServerName()
                     + ":" +request.getServerPort();
             System.out.println("Utils host:" +host);
             return host;
         }
     }
  • ok,就是这么简单

   转载规则

《SpringBoot之拦截器优雅注入请求根目录到request中字》GajAngels 采用 知识共享署名-非商业性使用 4.0 国际许可协议 进行许可。