Basic use of filter

The Filter Filter
It is one of the three main components of JavaWeb. Three components are: Servlet program, Listener, Filter Filter. Filter Filter is the JavaEE specification. It’s also the interface. The Filter Filter is used to intercept requests and Filter responses. Common application scenarios for intercepting requests are:
Permission checking diary operation transaction management requirements: Under your web project, there is an admin directory. All resources in the admin directory (HTML pages, JPG images, JSP files, and so on) must be logged in by the user before they can be accessed.

import com.wz.userManager.pojo.User;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(filterName = "UserCenterFilter",urlPatterns = {"/pages/*"})
public class UserCenterFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp= (HttpServletResponse)servletResponse;
        HttpSession session = req.getSession();
        User username = (User) session.getAttribute("user");
        if(username==null){
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}

Read More: