当前位置:网站首页>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

边栏推荐
- Industrial development status of virtual human
- Information update on automatic control principle
- String exercise summary 2
- Principle of IP routing
- [Software Engineering] key points at the end of the period
- Selection and comparison of message oriented middleware MQ
- Cross border e-commerce, early entry and early benefit
- Docker 安装 Redis-5.0.12,详细步骤
- Idea global search replace shortcut key
- 证件照处理
猜你喜欢

Kubevela v1.2 release: the graphical operation console velaux you want is finally here

Can AI chat robots replace manual customer service?
See how sparksql supports enterprise level data warehouse

NiO zero copy

结合源码剖析Oauth2分布式认证与授权的实现流程

Technology inventory: Technology Evolution and Future Trend Outlook of cloud native Middleware

The ktp900f mobile download program of the fail safe mobile panel prompts that the download cannot be performed, and the target device is running or not in the transmission mode

1. fully explain the basic principles of IPSec

FANUC机器人_KAREL编程入门学习(1)

Basic principles of spanning tree protocol
随机推荐
How to compare two or more distributions: a summary of methods from visualization to statistical testing
[Software Engineering] key points at the end of the period
Row and column differences in matrix construction of DX HLSL and GL glsl
C language operators and expressions
Learn more about the practical application of sentinel
A girl has been making hardware for ten years. 。。
Creating files, recursively creating directories
Information update on automatic control principle
String exercise summary 2
[QT] QT event handling
04A interrupt configuration
The ktp900f mobile download program of the fail safe mobile panel prompts that the download cannot be performed, and the target device is running or not in the transmission mode
Docker installs redis-5.0.12. Detailed steps
Development of live broadcast software app, and automatic left-right sliding rotation chart advertising
证件照处理
Web攻击之CSRF和SSRF
Learning notes 23-- basic theory of multi-sensor information fusion (Part I)
Industrial development status of virtual human
DX 的 HLSL 和 GL 的 GLSL的 矩阵构建的行列区别
NIO、BIO、AIO