zoukankan      html  css  js  c++  java
  • Spring的拦截器和监听器

    拦截器代码如下:

    package com.mengyao.shops.interceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    
    public class ShopInterceptor extends HandlerInterceptorAdapter {
    
        private Logger logger = LoggerFactory.getLogger(ShopInterceptor.class);
    
        
        @Override
        public void afterCompletion(HttpServletRequest request,
                HttpServletResponse response, Object handler, Exception ex)
                throws Exception {
            super.afterCompletion(request, response, handler, ex);
        }
    
        /**
         * Request结束后执行(Controller执行完成后)
         */
        @Override
        public void postHandle(HttpServletRequest request,
                HttpServletResponse response, Object handler,
                ModelAndView modelAndView) throws Exception {
            logger.info("==== {} ====", response.getStatus());
            super.postHandle(request, response, handler, modelAndView);
        }
    
        /**
         * Request的预处理(Controller之前执行)
         */
        @Override
        public boolean preHandle(HttpServletRequest request,
                HttpServletResponse response, Object handler) throws Exception {
            String userAddr = request.getRemoteAddr();  
            String url = request.getRequestURL().toString();
            logger.info("==== [userAddr:{}\t访问:{}] ====", userAddr, url);
            return true;
        }
    
    }

    监听器代码如下:

    package com.mengyao.shops.listener;
    
    import org.springframework.context.ApplicationListener;
    import org.springframework.context.event.ContextRefreshedEvent;
    
    public class InitListener implements ApplicationListener<ContextRefreshedEvent>  {
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            if(event.getApplicationContext().getParent() == null){
                //获取到父容器,即顶级容器
            }
        }
    
    }
  • 相关阅读:
    近来几个有用的网站
    军事视频网站
    美军武器命名
    区块链的五个关键要素
    处理多媒体的两个重要工具
    Python re模块将字符串分割为列表
    Python 自动刷新网页
    selenium:chromedriver与chrome版本的对应关系
    怎么批量删除QQ空间说说?
    ssm获取数据库名称
  • 原文地址:https://www.cnblogs.com/mengyao/p/4931579.html
Copyright © 2011-2022 走看看