拦截器

webConfig

//@EnableWebMvc 这个注解是一个坑,开启这个注解意味着所有的配置都要自己做,开启了之后要自己再写一个静态资源映射,否则直接在WebMvcConfigurer写exclude是不生效的

@Configuration
//@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    SessionInterceptor sessionInterceptor;

    @Bean  //将组件注册到容器中
    public WebMvcConfigurer webMvcConfigurer() {
        WebMvcConfigurer configurer = new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(sessionInterceptor).addPathPatterns("/**")
                        .excludePathPatterns("/static/**", "/webjars/**","/index");
                ;//所有路径,所以静态资源也被拦截了
            }
        };
        return configurer;
    }}

登陆拦截

对所有的请求都去查有没有名为“token”的cookie,如果有的话,就给session一个attribute。
相当于拿着银行卡(cookie)去银行,银行可以查到你是有这个账户存在的(session),就给这个账户命名为user

@Service
public class SessionInterceptor implements HandlerInterceptor {
    @Autowired
    UserMapper userMapper;
    @Autowired
    NotificationServiceImpl notificationService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length != 0) {
            for (Cookie cookie : cookies
            ) {
                if (cookie.getName().equals("token")) {
                    String token = cookie.getValue();
                    QueryWrapper<User> queryWrapper = new QueryWrapper();
                    queryWrapper.eq("token", token);
                    List<User> users = userMapper.selectList(queryWrapper);
                    if (users.size() != 0) {
                        HttpSession session=request.getSession();
                        session.setAttribute("user",users.get(0));
                        int unreadCount = notificationService.unreadCount(users.get(0).getId());
                        session.setAttribute("unreadCount", unreadCount);
                    }
                    break;
                }}}
        return true;
    }
}

webConfig的其他方法

webconfig的其他方法

 /**
     * 这个方法相当于创建了一个映射视图的Controler
     * /test请求匹配到test.html的视图去
     */
  @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/test").setViewName("test");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //设置自己的资源映射。如果启动了@EnableWebMvc,这个是要写的,否则所有的img、css静态资源都会被拦截
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值