Springboot | Seventh chapter: Filters, monitors, interceptors

Source: Internet
Author: User

Objective

In the actual development process, often encounter some such as system startup initialization information, statistics online number, online users, filter high vocabulary, access rights control (URL level) and other business needs. These are generally irrelevant to the business, the business side is no relationship, the business only need to relate to their own internal business things. So the general realization of the above functions, will be more or less used today to prepare to explain, 过滤器 监听器 拦截器 to achieve the above functions.

    • Filter filters
      • Using webfilter annotation Configuration
      • Filterregistrationbean Way
    • Listener
    • Interception device
    • Request Link Description
    • At last
    • Cliché
Filter filters

Filter Filter , is Servlet a practical technology of the. Through the filter, the request can be intercepted, such as reading to session determine whether the user is logged in , determine the access request URL has access rights (black and white list) and so on. It is possible to preprocess the request primarily. Next, under springboot How to implement the filter function.

Using webfilter annotation Configuration

@WebFilterWhen Servlet3.0 the new annotations, originally implemented filters, need to be web.xml configured in, and now through this note, the startup will automatically scan automatic registration.

Write the Filter class:

//注册器名称为customFilter,拦截的url为所有@WebFilter(filterName="customFilter",urlPatterns={"/*"})@Slf4jpublic class CustomFilter implements Filter{    @Override    public void init(FilterConfig filterConfig) throws ServletException {        log.info("filter 初始化");    }    @Override    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)            throws IOException, ServletException {        // TODO Auto-generated method stub        log.info("doFilter 请求处理");        //对request、response进行一些预处理        // 比如设置请求编码        // request.setCharacterEncoding("UTF-8");        // response.setCharacterEncoding("UTF-8");        //TODO 进行业务逻辑                //链路 直接传给下一个过滤器        chain.doFilter(request, response);    }    @Override    public void destroy() {        log.info("filter 销毁");    }}

You can then add annotations to the Startup class @ServletComponentScan .

@SpringBootApplication@ServletComponentScan@Slf4jpublic class Chapter7Application {        public static void main(String[] args) {        SpringApplication.run(Chapter7Application.class, args);        log.info("chapter7 服务启动");    }}

After startup, the console output:

The filter is already in effect. However, when registering multiple filters, it is not possible to specify the order of execution, when using the web。xml configuration filter, you can specify the order of execution, but @WebFilter when used, there is no configuration property (need to cooperate @Order ), so the next introduction through the FilterRegistrationBean Filter registration.

--Tips--

    1. Through the name of the filter , the order of the conventions, such as LogFilter and AuthFilter , at this time AuthFilter will be more than LogFilter the first execution, because the first letter A than the L previous.
    2. by @Order specifying the order of execution, the smaller the value, the more first it executes
Filterregistrationbean Way

FilterRegistrationBeanIs springboot provided, this class provides a Setorder method that allows you to set the sort value for filter so that spring is sorted before registering the Web filter and then registering it sequentially.

Overwrite Filter

In fact, the output of @webfilter annotations can be. Nothing else has changed.

The startup class leverages the @bean registration Filterregistrationbean

@Bean    public FilterRegistrationBean  filterRegistrationBean() {        FilterRegistrationBean registration = new FilterRegistrationBean();        //当过滤器有注入其他bean类时,可直接通过@bean的方式进行实体类过滤器,这样不可自动注入过滤器使用的其他bean类。        //当然,若无其他bean需要获取时,可直接new CustomFilter(),也可使用getBean的方式。        registration.setFilter(customFilter());        //过滤器名称        registration.setName("customFilter");        //拦截路径        registration.addUrlPatterns("/*");        //设置顺序        registration.setOrder(10);        return registration;    }    @Bean    public Filter customFilter() {        return new CustomFilter();    }

When registering multiple Filterregistrationbean, you can register multiple

After starting, the effect is the same as the first.

Listener

Listeeshi is a special class defined in the servlet specification. Used to listen for creation and destruction events for domain objects such as ServletContext, HttpSession, and ServletRequest. Listens to the properties of a domain object for modified events. Used to do the necessary processing before and after the event occurs. It is generally a business need to get people online.

Create a ServletRequest listener (other listeners like create)

@WebListener@Slf4jpublic class Customlister implements ServletRequestListener{    @Override    public void requestDestroyed(ServletRequestEvent sre) {        log.info("监听器:销毁");    }    @Override    public void requestInitialized(ServletRequestEvent sre) {        log.info("监听器:初始化");    }}

As with creating filters, you can add automatic registrations to the startup class @ServletComponentScan .

Interception device

The above filters and listeners belong to the Servlet API, and we can use the Spring provided interceptors ( HandlerInterceptor ) for finer control when we are dealing with the above filtering Web requests in development.

Writing Custom Interceptor Classes

@Slf4jpublic class CustomHandlerInterceptor implements HandlerInterceptor{    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)            throws Exception {        log.info("preHandle:请求前调用");        //返回 false 则请求中断        return true;    }    @Override    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,            ModelAndView modelAndView) throws Exception {        log.info("postHandle:请求后调用");    }    @Override    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)            throws Exception {        log.info("afterCompletion:请求调用完成后回调方法,即在视图渲染完成后回调");    }}

WebMvcConfigurerAdapterregistering interceptors by inheritance

@Configurationpublic class WebMvcConfigurer extends WebMvcConfigurerAdapter{        @Override     public void addInterceptors(InterceptorRegistry registry) {         //注册拦截器 拦截规则        //多个拦截器时 以此添加 执行顺序按添加顺序        registry.addInterceptor(getHandlerInterceptor()).addPathPatterns("/*");     }        @Bean    public static HandlerInterceptor getHandlerInterceptor() {        return new CustomHandlerInterceptor();    }}

After startup, access to a URL, console output

Request Link Description

Throughout the process of the request, this picture wins thousands of words, hoping to have a deep understanding of this, through different combinations to achieve different business functions.

Summarize

This chapter mainly introduces common Web development, the use of some common classes, this chapter servlet is not introduced, usually use less, usage and configuration in fact, and the interceptor, listener is similar, again not elaborated.

At last

At present, many big guys on the internet have a SpringBoot series of tutorials, if there is a similar, please forgive me. This article is the author in front of the computer word knocking, each step is practice. If there is something wrong in the text, also hope to put forward, thank you.

Cliché
    • Personal QQ:499452441
    • Public Number:lqdevOps

Personal blog: http://blog.lqdev.cn

Full instance Address: chapter-7

Original address: http://blog.lqdev.cn/2018/07/19/springboot/chapter-seven/

Springboot | Seventh chapter: Filters, monitors, interceptors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.