创建过滤器 ,实现用户未登录不能访问页面,登录完成之后进行正常访问

1.创建自定义过滤器LoginCheckFilter

//过滤器 检查用户是否已经完成登录
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")     //拦截所有请求
@Slf4j
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 response= (HttpServletResponse) servletResponse;


        //获取请求的url
        String requestURI=request.getRequestURI();

        //将不需要处理的请求放入数组
        String [] urls = new String[]{
             "/employee/login",
             "/employee/logout",
             "/backend/**",
             "/front/**"
        };
        boolean check=check(urls,requestURI);  //调用方法判断是否匹配到路径
        if (check){
            filterChain.doFilter(request,response);   //放行拦截到的请求
            return;
        }



          //判断是否登录,如果登录就放行
         if (request.getSession().getAttribute("employee") != null){
             filterChain.doFilter(request,response);   //放行拦截到的请求
             return;
         }

         //未登录进行拦截跳转到登录页面    //注意此代码是服务器响应给前端的代码,返回数据需要跟前端一致,由前端进行判断是否跳转到登录页面
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }


    //监测本次请求是否需要放行
    public boolean check(String[] urls,String requestURL){
        for (String url : urls) {
          boolean match=PATH_MATCHER.match(url,requestURL);
          if (match){
              return  true;
          }
        }
        return false;
    }
}

2.在启动类中增加注解@ServletComponentScan,用来开启过滤器

import org.springframework.boot.web.servlet.ServletComponentScan;

@Slf4j    //启动日志
@SpringBootApplication
@ServletComponentScan   //开启过滤器
public class ReggieApplication {
    //启动类
    public static void main(String[] args) {
        SpringApplication.run(ReggieApplication.class,args);
        log.info("项目启动成功");
    }
}

你可能感兴趣的:(java)