过滤器实现不登录无法查看页面中的数据

创建filter文件夹,创建对应的filter实现Filter接口

在这里插入图片描述

@Slf4j
@WebFilter(filterName = "loginChechkFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse responce = (HttpServletResponse) servletResponse;

        //1、获取本次请求的uri
        String requestURI = request.getRequestURI();

        //定义不拦截的uri
        String[] uris = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/favicon.ico"

        };
        //2、判断是否需要拦截
        if (check(uris,requestURI)){
            filterChain.doFilter(request,responce);
            return;
        }
        log.info("拦截到请求:{}",request.getRequestURI());
        log.info("登陆信息:{}",request.getSession().getAttribute("employee"));
        //3、判断是否登陆
        if (request.getSession().getAttribute("employee")!=null){
            filterChain.doFilter(request,responce);
            log.info("登陆信息:{}",request.getSession().getAttribute("employee"));
            return;
        }
        //4、没有登陆,返回主页面
        responce.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url,requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}

添加@ServletComponentScan注解

//com.huahuadeguozi.reggie_boot.ReggieBootApplication
@SpringBootApplication
@Slf4j
@ServletComponentScan
public class ReggieBootApplication {

    public static void main(String[] args) {

        SpringApplication.run(ReggieBootApplication.class, args);
        log.info("程序启动");
    }

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值