What 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
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!

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

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

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

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]

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

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
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment