package com.mahe666.filter;

import com.mahe666.util.Constant;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }
    //第二种实现方式 -- 过滤器
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //我们在Servlet中使用的HttpServletRequest和过滤器中的ServletRequest是父子关系
        //ServletRequest拿不到session，所以我们需要强转一下
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if (request.getSession().getAttribute(Constant.USER_SESSION) == null){
            response.sendRedirect("/error.jsp");
        }


        //先写这个语句，不要让请求和响应走到这里就卡死了
        filterChain.doFilter(servletRequest,servletResponse);
    }

    public void destroy() {

    }
}
