In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you how to use the filter Filter in SpringBoot, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
i. Background
Before we officially begin, it is necessary to take a brief look at what a Filter is and what this is for.
1. Filter description
Filter, the filter, belongs to the Servlet specification and is not unique to Spring. Its function can also be seen from the naming, intercept a request, do some business logic operations, and then decide whether the request can continue to be distributed to another Filter or the corresponding Servlet.
Briefly describe the workflow of a Filter after the next http request:
First go to filter and execute the relevant business logic.
If the traffic is determined, the Servlet logic is entered. After the Servlet execution is completed, the Filter is returned, and finally, it is returned to the requester.
If the judgment fails, return it directly. There is no need to send the request to Servlet.
Interruption: the above process is similar to the effect of @ Around in AOP around the section
two。 Project building
Next, let's build a web application to facilitate subsequent demonstrations. Building a web application with SpringBoot is a relatively simple task.
Create a maven project with the following pom file
Org.springframework.boot spring-boot-starter-parent 2.1.7 UTF-8 UTF-8 Finchley.RELEASE 1.8 org.springframework.boot spring-boot-starter-web com.alibaba fastjson 1.2.45 org.springframework.boot spring-boot-maven-plugin Spring-milestones Spring Milestones https://repo.spring.io/milestone false II. Filter tutorial 1. instructions
In the SpringBoot project, if you need to customize a Filter and there is nothing special, you can simply implement the interface, such as the following interceptor that outputs the request log
@ Slf4j@WebFilterpublic class ReqFilter implements Filter {public ReqFilter () {System.out.println ("init reqFilter");} @ Override public void init (FilterConfig filterConfig) throws ServletException {} @ Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request; log.info ("url= {}, params= {}", req.getRequestURI (), JSON.toJSONString (req.getParameterMap () Chain.doFilter (req, response);} @ Override public void destroy () {}}
It is easy to implement a custom Filter. There are usually two steps.
Implement the Filter interface
Add business logic to the doFilter method, and if the access is allowed to continue, execute chain.doFilter (req, response);; do not execute the above sentence, then the access ends here
The next question is how to make our custom Filter take effect. There are two common ways to use it in SpringBoot projects.
@ WebFilter
Packaging Bean: FilterRegistrationBean
A. WebFilter
This comment belongs to Servlet3+, and has nothing to do with Spring, so the question is, when I add this comment to Filter, how does Spring make it work?
The configuration file shows the use of the annotation @ ServletComponentScan
@ ServletComponentScan@SpringBootApplicationpublic class Application {public static void main (String [] args) {SpringApplication.run (Application.class);}}
The common attributes of WebFilter are as follows, of which urlPatterns is the most commonly used, indicating which url requests this filter applies to (all requests are intercepted by default)
The attribute name type describes the name attribute of the filterNameString specified filter, which is equivalent to valueString [], which is equivalent to the urlPatterns attribute. But both should not be used at the same time. UrlPatternsString [] specifies the URL matching pattern for a set of filters. Equivalent to a label. ServletNamesString [] specifies which Servlet the filter will be applied to. The value is either the value of the name attribute in @ WebServlet or the value of web.xml. DispatcherTypesDispatcherType specifies the forwarding mode of the filter. Specific values include: ASYNC, ERROR, FORWARD, INCLUDE, REQUEST. InitParamsWebInitParam [] specifies a set of filter initialization parameters, which are equivalent to labels. AsyncSupportedboolean declares whether the filter supports asynchronous operation mode, which is equivalent to the tag. DescriptionString the description of the filter, which is equivalent to the label. DisplayNameString the display name of the filter, usually used with the tool, is equivalent to the label. B. FilterRegistrationBean
The above method is relatively simple, but we will talk about a small problem later. It is troublesome to specify the priority of Filter.
Here is how to register using the wrapper bean
@ Beanpublic FilterRegistrationBean orderFilter () {FilterRegistrationBean filter = new FilterRegistrationBean (); filter.setName ("reqFilter"); filter.setFilter (new ReqFilter ()); / / specify priority filter.setOrder (- 1); return filter;} 2. common problem
When the above is done, you can begin to test the use of the filter. Before entering the actual measurement, let's take a look at two common questions.
Filter, as a component of Servelt, how to interact with Bean in SpringBoot
How to determine the priority between multiple Filter
A. Filter dependency Bean injection problem
If some partners use SpringMVC + web.xml to define Filter, they will find that @ Autowired cannot be used to inject Spring's bean into the custom Filter.
I used to use spring4 Servlet2+, there is a problem above, if you have a different point of view, please leave a message to let me know, thank you
Dependent Bean can be injected directly into SpringBoot. As you can see from the second registration method above, Spring encapsulates Filter into a Bean object, so you can directly inject dependent Bean.
The following defines an AuthFilter that relies on a custom DemoBean
@ Data@Componentpublic class DemoBean {private long time; public DemoBean () {time = System.currentTimeMillis ();} public void show () {System.out.println ("demo beanboxes!" + time);}} @ Slf4j@WebFilterpublic class AuthFilter implements Filter {@ Autowired private DemoBean demoBean; public AuthFilter () {System.out.println ("init autFilter") } @ Override public void init (FilterConfig filterConfig) throws ServletException {} @ Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {log.info ("in auth filter! {}", demoBean); / / Test, use the tx-demo in header to determine whether it is an authentication request HttpServletRequest req = (HttpServletRequest) request; String auth = req.getHeader ("tx-demo") If ("yihuihui" .equals (auth)) {/ / access is only allowed for authenticated requests. If this is not in the request header, the following method is not executed, then the request is filtered / / the following comment / / chain.doFilter (request, response) is opened during the test priority;} else {chain.doFilter (request, response) } @ Override public void destroy () {}} b. Priority assignment
Filter priority assignment, through my actual test, @ Order annotation is useless, inheriting Ordered interface is useless, no longer consider the web.xml scenario, can only specify priority when registering Bean
Examples are as follows: three Filter, two registered by @ WebFilter annotation and one registered by FilterRegistrationBean
@ Slf4j@Order (2) @ WebFilterpublic class AuthFilter implements Filter, Ordered {...} @ Slf4j@Order (1) @ WebFilterpublic class ReqFilter implements Filter, Ordered {...} @ Slf4jpublic class OrderFilter implements Filter {} @ ServletComponentScan@SpringBootApplicationpublic class Application {FilterRegistrationBean filter = new FilterRegistrationBean (); filter.setName ("orderFilter"); filter.setFilter (new OrderFilter ()); filter.setOrder (- 1); return filter } public static void main (String [] args) {SpringApplication.run (Application.class);}} 3. test
Three Filter are defined above, and we mainly verify the priority. If the @ Order annotation is valid, then the order of execution should be
OrderFilter-> ReqFilter-> AuthFilter
If it is not in the above order, then the @ Order annotation is useless
RestControllerpublic class IndexRest {@ GetMapping (path = {"/", "index"}) public String hello (String name) {return "hello" + name;}}
(the source code of the screenshot above is from: org.apache.catalina.core.ApplicationFilterFactory#createFilterChain)
The above is a screenshot of the breakpoints of the critical links during the test. From the array, we can see that the priority of AuthFilter is higher than that of ReqFilter. The actual output below also shows that the @ Order annotation cannot specify the priority of Filter. (I don't know why there are so many articles on the network that use Order to specify Filer priority!)
Our next question is what is the priority of the Filter registered with WebFilter annotations. We still look at it through debug, and the key code path is: org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#selfInitialize.
OrderFiler is that we manually register and set the priority to-1.
ReqFilter and AuthFilter are registered through WebFillter. The default priority is 2147483647. In the case of the same priority, it is determined according to the order of names.
iii. Summary
This article mainly introduces the use of the filter Filter, as well as two common questions and answers. The content of the article is interspersed with a little screenshot of the source code analysis, but it is not in-depth. If you are interested, you can explore some key positions mentioned in the article.
The following is a brief summary of the following
1. Filter usage
Implementation of custom Filter
Implement the Filter interface
In the doFilter method, the call chain.doFilter (request, response) is displayed; it indicates that the request continues; otherwise, the request is filtered
Registration becomes effective
@ ServletComponentScan automatically scans Filter with @ WebFilter annotations
Create Bean: FilterRegistrationBean to wrap the custom Filter
2. IoC/DI
Filter can be used like a normal Bean in SpringBoot, injecting its dependent Spring Bean objects directly through Autowired
3. Priority
Specify the priority when you create the FilterRegistrationBean, as follows
@ Beanpublic FilterRegistrationBean orderFilter () {FilterRegistrationBean filter = new FilterRegistrationBean (); filter.setName ("orderFilter"); filter.setFilter (new OrderFilter ()); filter.setOrder (- 1); return filter;}
In addition, note that @ WebFilter declares Filter with a priority of 2147483647 (lowest priority)
@ Order annotations cannot specify Filter priority
@ Order annotations cannot specify Filter priority
@ Order annotations cannot specify Filter priority
The above is all the content of the article "how to use filter Filter in SpringBoot". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.