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 1d24e586ca31f4bd05eca427459d98c7 tag in the above code specifies the name and class path of Filter. The dd0dfb26ea66647667f179a739921d33 tag specifies the mapping rules of the Filter, that is, which URLs the Filter intercepts.
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.
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.
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() { // 销毁操作 } }
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!