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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
