White road springboot of (xiii), filter, listener, interceptors

0 Introduction

  Filter, listener, often you need to use interceptors in the actual development, let's introduce the spring boot how to use;

First, the filter ----- ------

1, the role:

  Filters are between a client and a server resource file filter can help filter some of us do not meet the requirements of the request, can intercept resource requests (such as images, files, etc.) server to achieve some special features as well as giving special response;

  Used for checking session, user rights determination, filtered sensitive words, in response to the compression information, and other control-level access URL

2, to achieve:

  Using filters is very simple, just need to implement the Filter class, rewriting his three methods can be:

init: method performed when creating a filter;
destroy: the method of performing the filter destroy 

doFilter: a main method, the processing logic; There are three parameters, request information may be obtained by them;


1) Create a filter class LogFilter, add annotations @WebFilter

package com.anson.common.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;

/**
 * @description: 过滤器
 * @author: anson
 * @Date: 2019/12/20 6:03
 */

@WebFilter(filterName = "logfilter1", urlPatterns = "/*")
public class LogFilter implements Filter
{
    private static final Logger logger = LoggerFactory.getLogger(LogFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

        logger.info("----------------------->过滤器被创建");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponseWrapper resp = new HttpServletResponseWrapper((HttpServletResponse) servletResponse);

        String requestURI = req.getRequestURI();
        logger.info("--------------------->过滤器:请求地址"+requestURI); //记录请求
        if(requestURI.contains("info")){
           // servletRequest.getRequestDispatcher("/failed").forward(servletRequest, servletResponse);
            resp.sendRedirect("/failed");
        }else{
            the FilterChain.doFilter (servletRequest, ServletResponse); 
        } 
    }

    @Override 
    public  void the destroy () { 

        logger.info ( " -----------------------> filter is destruction " ); 
    } 
}

2) adding @ServletComponentScan notes on startup class

@ServletComponentScan ( " com.anson.common " ) // used to support the filter, listener comment

To

Note: The above notes we used the automatic registration mode, filter mode code is also registered (slightly) can be used, you can choose one yourself;

Second, the listener ----- -----

1, the role:

  The occurrence of listeners to listen for web application used to create the object, destroy, add, modify, delete the action, and make the appropriate response processing;

  Commonly used in statistics Online, traffic, system load initialization information;

2, classification:

ServletContextListener: the corresponding application, for monitoring attributes ServletContex operation;
HttpSessionListener: the corresponding session, for monitoring session object, commonly used in statistics is online;
ServletRequestListener: corresponding to the request, listen request object attribute operation;

3, to achieve:

1} create Listeners OnlineSessionListener

package com.anson.common.listener;

import com.anson.common.exception.GlobalExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
//import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
//import javax.servlet.http.HttpSessionEvent;
//import javax.servlet.http.HttpSessionListener;

/**
 * @description: TODO
 * @author: anson
 * @Date: 2019/12/20 6:48
 */
@WebListener 
public  class OnlineSessionListener the implements   of ServletContextListener   // the HttpSessionListener 
{
     Private  static  Final Logger Logger = LoggerFactory.getLogger (OnlineSessionListener. Class ); 

    @Override 
    public  void the contextInitialized (ServletContextEvent ServletContextEvent) 
    { 
        logger.info ( "the system start" ); 
        the System.out .println ( "the system start" ); 
    } 

    @Override 
    public  void  contextDestroyed(ServletContextEvent servletContextEvent)
    { 
        logger.info ( "stop system"); 
        System.out.println ( "the system stops" ); 
    } 

    // =============================
 //     public int = 0 online static;
 // 
//     @Override
 //     public void sessionCreated (HttpSessionEvent HttpSessionEvent)
 //     {
 // 
//         online ++;
 //         logger.info ( "on-line with a user, current line number:" + online);
 //         System.out.println ( "on-line with a user, current line number:" online +);
 //     }
 // 
//     @Override
 //     public void the sessionDestroyed (HttpSessionEvent HttpSessionEvent)
 //     {
 //         Online -;
 //         logger.info ( "users off the assembly line, the current line number:" + Online);
 //         under System.out.println ( "users line, the current line number: "+ online);
 //     } 
}

2) adding @ServletComponentScan notes on startup class

@ServletComponentScan ( "com.anson.common") // used to support the filter, listener comment

To

Note: The above notes we used the automatic registration mode, filter mode code is also registered (slightly) can be used, you can choose one yourself;

 

Third, the interceptor ------ ------

1, the role:

  Interceptor to intercept the object is dynamically invoked action, so some operations may be added before or after action, stop operation may be performed before the action;

  Commonly used in login authentication, operation log records, and other general processing;

2, to achieve:

  Using filters is very simple, only need to implement HandlerInterceptor class, rewriting his three methods can be:

The preHandle : is called before the processing request;
postHandle : requests to perform after call;
afterCompletion : After the call request is fully processed dispatcharservlet, commonly used in recording time consuming, some resources can be used for processing operations; 

1) prepared based interceptor MyInterceptor
package com.anson.common.interceptor;

import com.anson.common.exception.GlobalExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 拦截器
 * @author: anson
 * @Date: 2019/12/20 7:23
 */

@Component
public class MyInterceptor implements HandlerInterceptor
{
    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception
    {
        logger.info("afterCompletion被调用");
        long startime = (Long) arg0.getAttribute("startime");
        logger.info("请求耗时:"+ (System.currentTimeMillis() - startime));
    }

    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception
    {
        logger.info("postHandle被调用");
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {

        logger.info("preHandle被调用");
        request.setAttribute("startime",System.currentTimeMillis());
        return true;
    }
}

2) increase the allocation class AppConfigurer, registered interceptors

package com.anson.config;

import com.anson.common.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @description: 配置类
 * @author: anson
 * @Date: 2019/12/20 7:35
 */
@Configuration
public class AppConfigurer implements WebMvcConfigurer
{
    @Autowired
    private MyInterceptor myInterceptor;

    //注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(myInterceptor);
    }
}

To

Fourth, Postscript

  Simple use of filters, interceptors, is one such listener, including talk behind AOP, they are on some functions are crossed, according to actual needs the flexibility to choose;

 

Guess you like

Origin www.cnblogs.com/yanghj/p/12071296.html