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

边栏推荐
- Technology inventory: Technology Evolution and Future Trend Outlook of cloud native Middleware
- ACL (access control list) basic chapter - Super interesting learning network
- Feign project construction
- Leetcode: push domino (domino simulation)
- Combine pod identity in aks and secret in CSI driver mount key vault
- Creating files, recursively creating directories
- ThreadLocal memory leak
- 2022-06-16 工作记录--JS-判断字符串型数字有几位 + 判断数值型数字有几位 + 限制文本长度(最多展示n个字,超出...)
- 磁盘的结构
- Learning notes 23-- basic theory of multi-sensor information fusion (Part I)
猜你喜欢

1. fully explain the basic principles of IPSec

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...)
![[personal experiment report]](/img/04/c9e1bee19bff9d55b73c531f7b17f4.png)
[personal experiment report]

Fanuc robot_ Introduction to Karel programming (1)

ThreadLocal memory leak

How to compare two or more distributions: a summary of methods from visualization to statistical testing

2022-06-10 work record --js- obtain the date n days after a certain date

Embedded development: tips and tricks -- clean jump from boot loader to application code

Virtual private network foundation

MySQL + JSON = King fried!!
随机推荐
中国SSD行业企业势力全景图
上新了,华为云开天aPaaS
CDN principle
VRRP skills topic
故障安全移动面板KTP900F Mobile下载程序提示无法下载,目标设备正在运行或未处于传输模式的解决办法
Kubevela v1.2 release: the graphical operation console velaux you want is finally here
堆内存分配的并发问题
[Software Engineering] key points at the end of the period
JWT(Json Web Token)
Online filing process
Wechat side: what is consistent hash? In what scenario? What problems have been solved?
find your present (2)
High level application of SQL statements in MySQL database (II)
Annotation
How to compare two or more distributions: a summary of methods from visualization to statistical testing
Combine pod identity in aks and secret in CSI driver mount key vault
Data center basic network platform
[personal experiment report]
See how sparksql supports enterprise level data warehouse
Future development of education industry of e-commerce Express