Filter (interceptor)

The role of the filter

The purpose of Servlet is to process the request initiated by the browser
. We can flexibly handle the request by the Servlet technology,
but we should not only deal with the request, the server resources we need to
source unified management, unified set of such request, funded encoding format
uniform distribution sources, etc., What should I do at this time?

Use filters to intercept and perform some preprocessing before the servlet receives the request.

use

Create a common java class that implements the Filter interface.
Override the method of the
init method: the server starts and executes. Resource initialization
doFilter method: A method of intercepting requests, in which resources can be managed.
Note: The
request needs to be released manually. chain.doFilter (request, response);
destory method: the server shuts down and executes.
Configure the filter in web.xml

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

Note:
url-pattern: / *
means to intercept all requests.
url-pattern: *
.do means all requests ending in .do. Generally used for module interception processing.
url-pattern: / ts
means to intercept the request of the specified url. Intercept the request of a servlet to protect the servlet.

principle

The browser initiates a request to the server, and after receiving the request, the server finds the corresponding filter in web.xml and executes the doFilter method according to the URI information. This method processes the request if it meets the requirements and releases it. The filtering that meets the requirements will continue to filter and find the corresponding servlet to perform the request processing. After the servlet processes the request, the service method ends. Need to continue to return to the corresponding doFilter method to continue execution.

Case

Unified coding format setting.
session management
authority management
resource management (unified watermark, harmonious vocabulary, etc.)

Published 66 original articles · won praise 5 · Views 3492

Guess you like

Origin blog.csdn.net/weixin_44001681/article/details/105543558