Java拦截器
一、InterceptorRegister
package com.muen.interceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class InterceptorRegister extends WebMvcConfigurerAdapter { private static final Logger logger = LoggerFactory.getLogger(InterceptorRegister.class); @Override public void addInterceptors(InterceptorRegistry registry) { InterceptorRegistration ir = registry.addInterceptor(new MyInterceptor()); /** 拦截所有路径 */ /* ir.addPathPatterns("/**"); */ /** 不拦截获取验证码请求路径 */ /* ir.excludePathPatterns("/getBizId"); */ /** 拦截个人中心 */ ir.addPathPatterns("/Accounts/**"); /** 拦截家庭档案 */ ir.addPathPatterns("/FamilyFile/**"); /** 拦截健康档案 */ ir.addPathPatterns("/HealthyArchives/**"); /** 健康自测 */ ir.addPathPatterns("/HealthTest/**"); /** 体检报告 */ ir.addPathPatterns("/ExamineReport/**"); /** 家庭医生 */ ir.addPathPatterns("/familydoctor/**"); /** 指标趋势 */ ir.addPathPatterns("/canvasManage/**"); super.addInterceptors(registry); } }
二、MyInterceptor
package com.muen.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.muen.util.Constants; import com.muen.util.StringUtils; /** * @author MyPC */ public class MyInterceptor implements HandlerInterceptor { private Logger logger = Logger.getLogger(MyInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("preHandle..."); String path = request.getServletPath(); // 不需要的拦截直接过;不需要拦截的请求配置在这个属性里面加 if (path.matches(Constants.NO_INTERCEPTOR_PATH)) { return true; } else { // TODO:这写你拦截需要干的事儿,比如各种判断等 //没有登录 if (StringUtils.isBlank(request.getSession().getAttribute("personalInfo"))) { if (StringUtils.isBlank(request.getSession().getAttribute("personalBaseInfo"))) { logger.info("没有登录,被拦截了,跳转到登录页面..."); request.getRequestDispatcher("/personal/login").forward(request, response); return false; } else { return true; } } return true; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { logger.info("postHandle..."); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { logger.info("afterCompletion..."); } }
PS:根据项目需求自行修改
作者:情殇
-------------------------------------------
个性签名:“深入浅出,骑上拔下” 此乃大道
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!