search
HomeJavajavaTutorialWhat are the functions, types and application scenarios of Filter in Java?

    How to use Filter

    In Java Web applications, using Filter is very simple, just write a class that implements the javax.servlet.Filter interface, and then Configure Filter in the web.xml configuration file to use Filter. The following is a code example of Filter:

    public class MyFilter implements Filter {
        public void init(FilterConfig filterConfig) throws ServletException {
            // 初始化操作
        }
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            // 过滤器逻辑处理
            chain.doFilter(request, response);
        }
        public void destroy() {
            // 销毁操作
        }
    }

    Configure Filter in the web.xml configuration file:

    <filter>
        <filter-name>MyFilter</filter-name>
        <filter-class>com.example.MyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    The tag in the above code specifies the name and class path of Filter. The tag specifies the mapping rules of the Filter, that is, which URLs the Filter intercepts.

    Filter’s life cycle

    Filter’s life cycle has three methods: init(), doFilter() and destroy().

    init() method: called when Filter is created, used to initialize Filter. This method will only be called once.

    When the interceptor captures each request, the doFilter() method is called to process the request and response. If you need to continue executing the next Filter, you need to call the chain.doFilter(request, response) method, otherwise you do not need to call this method.

    destroy() method: called when the Filter is destroyed, used to release resources.

    Filter execution order

    In the web.xml configuration file, multiple Filters can be configured, and their execution order is executed in the order defined in the configuration file. For example:

    <filter>
        <filter-name>FilterA</filter-name>
        <filter-class>com.example.FilterA</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>FilterA</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>FilterB</filter-name>
        <filter-class>com.example.FilterB</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>FilterB</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    In the above configuration, FilterA will be executed first, and then FilterB will be executed.

    Filter details

    Automatic login

    In web applications, it is usually necessary to implement the automatic login function, that is, after the user successfully logs in, he does not need to enter it again the next time he visits. User name and password, just access directly. The following is a simple automatic login idea:

    • When the user logs in, the user name and password are saved in Cookie.

    • Determine in the Filter whether the user has logged in. If not, determine whether a cookie exists. If a cookie exists, automatically fill in the username and password in the cookie into the login form. Verify your login again.

    The following is a simple code example for logging in to Servlet:

    public class LoginServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            // 获取用户名和密码
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            // 验证用户名和密码
            if ("admin".equals(username) && "123456".equals(password)) {
                // 登录成功,保存用户信息到Session中
                HttpSession session = request.getSession();
                session.setAttribute("username", username);
                // 保存自动登录信息到Cookie中
                Cookie cookie = new Cookie("autologin", username + ":" + password);
                cookie.setMaxAge(7 * 24 * 60 * 60); // 设置Cookie过期时间为一周
                response.addCookie(cookie);
                // 跳转到首页
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            } else {
                // 登录失败,返回登录页面
                response.sendRedirect(request.getContextPath() + "/login.jsp");
            }
        }
    }

    The following is a simple code example for automatically logging into Filter:

    public class AutoLoginFilter implements Filter {
        public void init(FilterConfig filterConfig) throws ServletException {
            // 初始化操作
        }
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            // 判断用户是否已经登录
            HttpSession session = ((HttpServletRequest) request).getSession();
            String username = (String) session.getAttribute("username");
            if (username == null) {
                // 判断是否存在Cookie
                Cookie[] cookies = ((HttpServletRequest) request).getCookies();
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if ("autologin".equals(cookie.getName())) {
                            // 自动填充用户名和密码
                            String[] values = cookie.getValue().split(":");
                            String autologinUsername = values[0];
                            String autologinPassword = values[1];
                            request.setAttribute("autologinUsername", autologinUsername);
                            request.setAttribute("autologinPassword", autologinPassword);
                        }
                    }
                }
            }
            chain.doFilter(request, response);
        }
        public void destroy() {
            // 销毁操作
        }
    }

    BeanUtils Use

    In Web development, we usually need to convert form data into JavaBean objects, and this function can be achieved using the BeanUtils tool class. Use BeanUtils to encapsulate form data into JavaBean objects, thereby simplifying form data processing. The following is an example of using BeanUtils:

    public class UserServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            // 获取表单数据
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            int age = Integer.parseInt(request.getParameter("age"));
            // 将数据封装成User对象
            User user = new User();
            try {
                BeanUtils.setProperty(user, "username", username);
                BeanUtils.setProperty(user, "password", password);
                BeanUtils.setProperty(user, "age", age);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 保存用户信息
            UserService userService = new UserService();
            userService.saveUser(user);
            // 跳转到用户列表页面
            response.sendRedirect(request.getContextPath() + "/user/list.jsp");
        }
    }

    In the above code, the form data is encapsulated into a User object through the BeanUtils.setProperty() method.

    The above is the detailed content of What are the functions, types and application scenarios of Filter in Java?. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

    The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

    How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

    The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

    How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

    The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

    How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

    The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

    How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

    Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Chat Commands and How to Use Them
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment