拦截器代码如下:
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){ //获取到父容器,即顶级容器 } } }