当前位置:网站首页>The difference between interceptor and filter
The difference between interceptor and filter
2022-06-24 22:42:00 【Passerby Chen】
filter (Filter)
Need to be in web.xml Middle configuration , Depend on servlet Containers , It's based on function callbacks . It can filter almost all requests , The drawback is that a filter instance can only be invoked once when the container is initialized . The purpose of using the filter , It's used to do some filtering operations , Get the data we want to get , such as : stay Javaweb in , The incoming request、response Filter out some information in advance , Or set some parameters in advance , And then pass in servlet perhaps Controller Do business logic operations . The usual scene is : Modify the character encoding in the filter (CharacterEncodingFilter)、 Modify in the filter HttpServletRequest Some parameters of (XSSFilter( Custom filter )), Such as : Filter vulgar text 、 Dangerous characters, etc .
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<servlet-name>/*</servlet-name>
</filter-mapping>Interceptor (Interceptor)
Interceptor (Interceptor) Need to be in SpringMVC Middle configuration , Depending on the framework , Is based on Java The reflection mechanism of
SpringMVC Interceptors in , amount to web Filters in development Filter, Used to deal with Controller Conduct Preprocessing ( Lead to enhance ) and post-processing ( The rear enhancement )
A chain of interceptors , be called The interceptor chain (Interceptor chain)
When access is blocked ( Specific goals Controller) When the method is used , Interceptors in the interceptor chain will be called in the previously defined order
Interceptors, too AOP The concrete realization of thought
preHandle Execute before the intercepted target method executes .
postHandle Execute after the intercepted target method has obtained the return value .
afterCompletion Execute after the target method finishes rendering the view layer .
Interceptor , When entering controller Intercept before .
Realization HandlerInterceptor Interface , preHandler Method , return true You can call controller Method ,false Will not call controller
Need to be in springmvc.xml To configure
effect : Access control ( authentication , Did you log in ), Link tracking of micro clothing , Record the user's access log
Interceptor (Interceptor) and filter (Filter) The difference between
| difference | filter Filter | Interceptor |
|---|---|---|
| Using range | yes Servlet Part of the norm , whatever Javaweb Projects can use | yes SpringMVC Their own , Only used SpringMVC frame , To use the interceptor |
| Interception range | Configured with urlPatterns="/*" after , All resources to be accessed can be intercepted | If you are configuring /** , Will intercept DispatcherServlet Captured resources ( request ) |
| Interception accuracy | Only one request can be intercepted , Not right Servlet In a certain method to intercept , | It can be fine to intercept Controller One of the ways in |
Interception accuracy answer :
because servlet When the mapping address is written inside , It is written on the class , One servlet There will only be one mapping address
controller Dissimilarity , There are many ways in it , Each method corresponds to a different path address .
Implementation steps
Create a Java class , Realization
Rewrite the interface method , There are three methods :HandlerInterceptorInterfacepreHandle, postHandle, afterCompletionstay springmvc.xml The interceptor is configured in
Create a Java class , Realization HandlerInterceptor Interface
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
Custom interceptors
1. Defining classes , Implementation interface HandlerInterceptor
2. Realization 3 A way : preHandle | postHandle | afterCompletion
3. Configure interceptors , What requests to intercept !
*/
public class MyInterceptor implements HandlerInterceptor {
/*
stay Controller Call this method before executing the method
1. In this method, it is decided whether to release or not !
2. The return value determines whether to release or not ! true : release , false : No release !
3. How to handle interception :
3.1 release , There's nothing to do here !
3.2 Intercept , To respond to this request :
3.2.1 You can write a sentence !
3.2.2 You can jump to a page !
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("MyInterceptor::preHandle...");
//1. After intercepting the request , Return a sentence !:
//response.setContentType("text/html;charset=utf-8");
//response.getWriter().write(" Blocking access !");
/*
2. After intercepting , You can jump to the page
2.1 Jump to the page , It is best to use an absolute path to jump ! Don't use relative paths !
*/
response.sendRedirect("/index.jsp");
return false;
}
// stay Controller After method execution , , Call this method before rendering the page
// If controller Method does not execute , So this postHandle And will not execute
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor::postHandle...");
}
// Execute... After page rendering !
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("MyInterceptor::afterCompletion...");
}
}
stay springmvc.xml The interceptor is configured in
<!--
Configure interceptors
mvc:interceptors : Specially configured interceptors , Many interceptors can be configured
mvc:interceptor : Configure detailed interceptors ,
mvc:mapping : What is the intercepted address path
path: Specific address path
bean: Specific interceptors
-->
<mvc:interceptors>
<mvc:interceptor>
<!--
Intercepted address interpretation :
1. General with / Lead
2. You can write the name of the specific interception , You can also use wildcards ** To intercept
/* == Only one level can be matched == lcoalhost:82/a , Can't match lcoalhost:82/a/b
/** == You can match directories at any level == lcoalhost:82/a | lcoalhost:82/a/b | lcoalhost:82/a/b/c/d
3. When configuring /** When , Interceptors can intercept DispatcherServlet All requests that can be captured
3.1 DispatcherServlet The configuration is /
3.2 controller Method ==== Can catch the request , So intercept
3.3 Static resources ==DispatcherServlet Requests that can catch static resources = Can catch the request , So intercept
3.4 jsp === DispatcherServlet Can't catch the request , So it won't intercept .
-->
<mvc:mapping path="/**"/>
<!-- You can also set to ignore some addresses here , Don't intercept !-->
<mvc:exclude-mapping path="/css/**"/>
<mvc:exclude-mapping path="/js/**"/>
<mvc:exclude-mapping path="/html/**"/>
<bean class="com.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>

The interceptor chain (Interceptor chain)
Interceptors are in chain mode
Only preHandler Method returns true release ,false Intercept
After interception, you also need to respond to this request ( Jump to the page | Jump Controller)
Interceptor execution method sequence preHandle->postHandle->afterCompletion
When there is an interceptor chain , Execute in the configuration file order , From top to bottom . advanced (preHandle) Later (postHandle,afterCompletion)
When our springmvc Static resource processing is configured , And the interceptor is configured to /** , Then the interceptor will also intercept static resources . If the interceptor must not intercept static resources :
Manually specify the path of the static resource , The interceptor then excludes specific static resources
mvc:default-servlet-handler and Interceptor /** Or write as usual
Need to be in web.xml in , add to DefaultServlet Mapping path for
<servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> <url-pattern>*.html</url-pattern> <url-pattern>*.js</url-pattern> </servlet-mapping>3.DispatcherServlet Intercept only *.do

边栏推荐
- See how sparksql supports enterprise level data warehouse
- Data communication foundation - Ethernet port mirroring and link aggregation
- Idea close global search box
- ACL (access control list) basic chapter - Super interesting learning network
- Information update on automatic control principle
- Introduction, installation and use of postman tool
- Web攻击之CSRF和SSRF
- 2022-06-16 work record --js- judge the number of digits in string type digits + judge the number of digits in numeric type digits + limit the text length (display n words at most, exceeding...)
- 上新了,华为云开天aPaaS
- A pit in try with resources
猜你喜欢

ThreadLocal local thread

Nuscenes -- remedies for missing image files or 0-size images encountered during dataset configuration

HTTP的缓存控制

Introduction, installation and use of postman tool

MySQL + JSON = King fried!!

ACL (access control list) basic chapter - Super interesting learning network

详细了解关于sentinel的实际应用

Data center basic network platform

Technology Review: what is the evolution route of container technology? What imagination space is there in the future?

重磅!法大大上榜“专精特新”企业
随机推荐
Industrial development status of virtual human
New features of go1.18: efficient replication, new clone API for strings and bytes standard library
YGG recent game partners list
详细了解Redis的八种数据类型及应用场景分析
Huada 04A operating mode / low power consumption mode
堆內存分配的並發問題
Web security XSS foundation 06
重磅!法大大上榜“专精特新”企业
中国SSD行业企业势力全景图
Nuscenes -- remedies for missing image files or 0-size images encountered during dataset configuration
YGG 近期游戏合作伙伴一览
Description of transparent transmission function before master and slave of kt6368a Bluetooth chip, 2.4G frequency hopping automatic connection
Annotation
【软件工程】期末重点
A pit in try with resources
In the first year of L2, arbitrum nitro was upgraded to bring more compatible and efficient development experience
O (n) complexity hand tear sorting interview questions | an article will help you understand counting sorting
HTTP的缓存控制
Introduction, installation and use of postman tool
Wechat side: what is consistent hash? In what scenario? What problems have been solved?