在业务处理器解决申请之前会调用prehandle() 【在这个办法中会进行一些前置初始化操作或者是对以后申请的一个预处理,也能够在这个办法中进行一些判断来决定申请是否要持续进行上来】如果该办法的返回值为true,则程序持续向下执行处理器中的办法,否则将不再向下执行——业务处理器解决完申请——**postHandler()—— 进行视图解析渲染——执行afterCompletion()办法——向客户端返回响应
配置拦截器:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration //等同于web.xml配置文件public class MvcConfigurer implements WebMvcConfigurer{@Autowiredprivate UserInterceptor userInterceptor;//开启匹配后缀型配置@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {//开启匹配后缀型配置 .htmlconfigurer.setUseSuffixPatternMatch(true);}/**** 拦挡相似购物车 和订单的所有申请 交给 咱们自定义的拦截器进行解决*/@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(userInterceptor). addPathPatterns("/cart/**","/order/**");}/**** 工夫拦截器配置*/ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new TimeAccessInterceptor()) .addPathPatterns("/user/doLogin");//设置要拦挡的url地址 }}
自定义工夫拦截器
public class TimeAccessInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandler()"); //获取java中的日历对象 LocalDateTime localDateTime=LocalDateTime.now(); //获取以后工夫对应的小时 int hour=localDateTime.getHour(); System.out.println("hour:"+hour); if(hour<=9.5||hour>=15.5) throw new ServiceException("请在9:30-15:30之间拜访"); return true; }}
电商我的项目自定义拦截器 登录
/** * 需要; 拦挡/cart 结尾的所有的申请进行拦挡,并且校验用户登录 * 拦截器抉择 preHandler * 如何判断用户是否登录: 1.查看cookie信息 2.查看Redis中是否有记录 * true:放行 false 申请应该拦挡 配合重定向 */@Componentpublic class UserInterceptor implements HandlerInterceptor { @Autowired private JedisCluster jedisCluster;//redis集群 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //1.判断用户是否登录 查看cookie是否有值 String ticket= CookieUtil.getCookieValue(request,"JT_TICKET"); //校验ticket if(!StringUtils.isEmpty(ticket)){ //判断redis中是否有值 if(jedisCluster.exists(ticket)){ return true; } } response.sendRedirect("/user/login.html");//拦挡申请 重定向到登录页面 return false; }}