Home Java javaTutorial Detailed introduction to Filter in JavaWeb

Detailed introduction to Filter in JavaWeb

Mar 16, 2017 am 10:14 AM

This article mainly introduces the detailed explanation of JavaWeb FilterFilter, and analyzes the usage skills of JavaWeb Filter with examples. It is of great practical value and friends in need can refer to it.

I originally planned to summarize this articleJSP. Since JSP has a lot of content, and I want to run at night to lose weight, I will introduce Filter and its usage examples today. There is still some time to exercise. Closer to home, the filter literally has the function of blocking and filtering. It can be regarded as the blocking wizard of JavaWeb.

1. Origin

#The client initiates a request, so the server cannot respond to all requests. Interception processing can not only alleviate the problem of the server It can also protect the security of the data. Similarly, when the server responds to the client, it sometimes needs to be filtered, such as adding watermarks to our common pictures. In order to deal with these problems, filters appeared. Sometimes not only one layer of requests and responses is filtered, but multiple layers may be filtered, so the concept of filter chain (FilterChain) is proposed.

II , Use

Be familiar with its function before using it. The filter function will pass through the filter chain in sequence before the request reaches Servlet and before the response reaches the browser. Somewhat similar to httpmodule in asp.net. Using Filter mainly implements javax.servlet.filterinterface. Looking at API, you can see that there are 3 methods.

1.public void init(FilterConfig filterConfig) throws ServletException

Called by the Web container to indicate the filter that will be put into the service . The servlet container calls the init method only once after instantiating the filter. The init method must complete successfully before asking the filter to do any filtering work. If the init method throws a ServletException or does not return within the time period defined by the web container, the web container cannot put the filter into the service. This is somewhat similar to the life cycle of Servlet. It is only initialized once and destroy() is also executed once.

2.public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException

Every time due to a certain error at the end of the chain When a client request for a resource passes a request/response pair through the chain, the container calls the Filter's doFilter method. The FilterChain passed into this method allows the Filter to pass the request and response to the next entity in the chain.
A typical implementation of this method follows the following pattern:

1. Check the request

2. Selectively send the request with a custom implementation Object Wrapping into filter content or headers for input filtering

3. Optionally wrap response objects with custom implementations into filter content for output filtering Or in the header

4. a) You can either use the FilterChain object (chain.doFilter()) to call the next entity in the chain,

4. b) Also It is possible to block request processing by not passing the request/response pair to the next entity in the filter chain

5. Set headers on the response directly after calling the next entity in the filter chain .

3.public void destroy()

Called by the web container to indicate the filter to be taken out of the service. This method is called only once after all threads in the filter's doFilter method have exited, or after the timeout period has elapsed. After calling this method, the web container will not call the doFilter method on this filter instance. This method provides an opportunity for the filter to clean up all resources it holds (such as memory, file handles, and threads) and ensures that any persistent state is kept in sync with the current state of the filter in memory.

3. Cases

There are many places to use filters, so I won’t give examples one by one here. The following demo is in the previous blog Based on the HelloWorld project, the anti-leeching function is implemented to experience the use of Filter.

1.Preparation

In the HelloWolrd projectAdd a new folder and put two pictures in the folder, one err.png and one test.png. The two pictures are as follows

2. Create Filter

There is no new Filter package here. Create the Filter file MyFilter directly in the com.test.cyw package in the previous blog. It should be to create a package specifically to manage Filter. Well, this is just for testing. After the creation is completed, you can see that MyFilter inherits Filter.


 public class MyFilter implements Filter
Copy after login

3. Implement anti-hotlinking in doFilter


package com.test.cyw;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;

/*@WebFilter("/MyFilter")*/
public class MyFilter implements Filter {

  public MyFilter() {
    
  }

  public void destroy() {
    
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
    HttpServletRequest req=(HttpServletRequest)request;
    HttpServletResponse res=(HttpServletResponse)response;
    String referer=req.getHeader("referer");//链接来源地址
    if(referer==null||!referer.contains(req.getServerName()))
    {
      req.getRequestDispatcher("/Images/err.png").forward(req, res);
      return;
    }
    chain.doFilter(req, res);
  }

  public void init(FilterConfig fConfig) throws ServletException {
    
  }
}
Copy after login

4.Filter configuration

The above just creates a class that implements the Filter interface. How to let Tomcat know? This is similar to Servlet and needs to be configured in Web.xml. It's a bit the same as configuring a servlet.


  <filter>
   <filter-name>MyFilter</filter-name>
   <filter-class>com.test.cyw.MyFilter</filter-class>
 </filter>
 <filter-mapping>
   <filter-name>MyFilter</filter-name>
   <url-pattern>/Images/*</url-pattern>
 </filter-mapping>
Copy after login

5. Test

Create a new test.jsp file, display img in jsp, and it can be displayed normally


 <%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<img alt="防盗链" src="Images/test.png" width="400">
</body>
</html>
Copy after login

If you directly enter the address of test.png in the browser, err.png

# will be displayed ##4. Problems Encountered

At the beginning, due to the wrong address, the image displayed in Google Chrome test.jsp was also the err.png picture, but when I When I refreshed the page, there was still no change. This made me very puzzled. Sometimes restarting Tomca doesn't work. I tried it several times and it still works like this. When it really doesn't work, I tried it with IE but didn't expect the display to be correct. It turns out that Google Chrome has a

cache, which caused the display to be incorrect.

5. Summary

Filter has many uses, and there are many examples on the Internet. When doing projects, you can first implement some commonly used ones such as watermarks, etc. When using it, you only need to configure the xml to solve the problem, which is very convenient.

The above is the detailed content of Detailed introduction to Filter in JavaWeb. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1254
24
How to Analyze Code Auditing in Java Web Security How to Analyze Code Auditing in Java Web Security May 16, 2023 am 08:04 AM

1. JavaWeb Security Basics 1. What is code auditing? In layman’s terms, Java code auditing is to discover security issues in the Java application itself by auditing Java code. Since Java itself is a compiled language, even if there are only class files We can still audit Java code. For uncompiled Java source code files, we can read the source code directly, but for compiled class or jar files, we need to decompile them. Java code auditing itself is not very difficult. As long as you are proficient in the auditing process and common vulnerability auditing techniques, you can complete the code auditing work relatively easily. But the way of Java code auditing is not just to use

Vue error: The filter in filters cannot be used correctly, how to solve it? Vue error: The filter in filters cannot be used correctly, how to solve it? Aug 26, 2023 pm 01:10 PM

Vue error: The filter in filters cannot be used correctly, how to solve it? Introduction: In Vue, filters are a commonly used function that can be used to format or filter data. However, during use, sometimes we may encounter problems with not being able to use the filter correctly. This article will cover some common causes and solutions. 1. Cause analysis: The filter is not registered correctly: Filters in Vue need to be registered before they can be used in templates. If the filter is not successfully registered,

How to solve the '[Vue warn]: Failed to resolve filter' error How to solve the '[Vue warn]: Failed to resolve filter' error Aug 19, 2023 pm 03:33 PM

Methods to solve the "[Vuewarn]:Failedtoresolvefilter" error During the development process using Vue, we sometimes encounter an error message: "[Vuewarn]:Failedtoresolvefilter". This error message usually occurs when we use an undefined filter in the template. This article explains how to resolve this error and gives corresponding code examples. When we are in Vue

PHP Email Filter: Filter and identify spam. PHP Email Filter: Filter and identify spam. Sep 19, 2023 pm 12:51 PM

PHP Email Filter: Filter and identify spam. With the widespread use of email, the amount of spam has also continued to increase. For users, the amount of spam they receive can lead to information overload and wasted time. Therefore, we need an efficient method to filter and identify spam emails. This article will show you how to write a simple but effective email filter using PHP and provide specific code examples. Basic Principle of Email Filter The basic principle of email filter is to determine whether the email is

How to filter and sort data in Vue technology development How to filter and sort data in Vue technology development Oct 09, 2023 pm 01:25 PM

How to filter and sort data in Vue technology development In Vue technology development, data filtering and sorting are very common and important functions. Through data filtering and sorting, we can quickly query and display the information we need, improving user experience. This article will introduce how to filter and sort data in Vue, and provide specific code examples to help readers better understand and use these functions. 1. Data filtering Data filtering refers to filtering out data that meets the requirements based on specific conditions. In Vue, we can pass comp

Filter function in Vue3: handle data elegantly Filter function in Vue3: handle data elegantly Jun 18, 2023 pm 02:46 PM

Filter Functions in Vue3: Handling Data Elegantly Vue is a popular JavaScript framework with a large community and a powerful plug-in system. In Vue, the filter function is a very practical tool that allows us to process and format data in templates. There have been some changes to the filter functions in Vue3. In this article, we will take a deep dive into the filter functions in Vue3 and learn how to use them to handle data gracefully. What is a filter function? In Vue, the filter function is

In PHP, the FILTER_VALIDATE_URL constant represents the filter used to validate URLs In PHP, the FILTER_VALIDATE_URL constant represents the filter used to validate URLs Sep 14, 2023 am 10:37 AM

The FILTER_VALIDATE_URL constant is used to validate URLs. The flag FILTER_FLAG_SCHEME_REQUIRED−URL must be RFC compliant. FILTER_FLAG_HOST_REQUIRED−URL must contain the hostname. FILTER_FLAG_PATH_REQUIRED−URL must have a path after the domain name. FILTER_FLAG_QUERY_REQUIRED−URL must have a query string. Return value FILTER_VALIDATE_URL

Tips for using plug-ins to implement custom filters in Vue Tips for using plug-ins to implement custom filters in Vue Jun 25, 2023 pm 05:01 PM

Tips for using plug-ins to implement custom filters in Vue Vue.js provides a convenient way to handle the need for view data filtering, that is, filter. Filters are mainly responsible for formatting and processing the data in the view to make the data more intuitive and easy to understand. Vue has some built-in commonly used filters, such as date formatting, currency formatting, etc., and also supports custom filters. This article will introduce how to use the Vue plug-in to implement custom filters and provide some practical filtering techniques.

See all articles