拦截器
文章目录

在业务处理器处理请求之前会调用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{
@Autowired
private UserInterceptor userInterceptor;
//开启匹配后缀型配置
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
//开启匹配后缀型配置 .html
configurer.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 请求应该拦截 配合重定向
*/
@Component
public 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;
}
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论