SpringBoot use of interceptors, filter, listener SpringBoot use interceptors, filter, listener

Excerpt: https://www.cnblogs.com/haixiang/p/12000685.html

SpringBoot use of interceptors, filter, listener

 



PS: the original link https://www.cnblogs.com/haixiang/p/12000685.html , please indicate the source

filter

Filter Introduction

The English name for the filter Filter, Servlet technology is the most practical technology. As its name suggests, it is in a filter between the client and server resource file filter to help filter out some of us do not meet the requirements of the request, commonly used as Session check to determine user privileges, if it does not set conditions, it will be blocked to a particular address or based on special response.

Use filters

We first need to implement  Filterthe interface and then rewrite it three methods

  • init method: create the current filter in the container when the automatic call
  • destory method: when the destruction of the current filter in the container automatically calls
  • doFilter method: in the specific operation of the filter

We first introduced Maven dependency, which is used to avoid lombok each file to print the log created Logger

        <dependency>
            <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

We first implement the interface, override three methods, we ask for the request contains four to be released, will be redirected to other request interceptor /online, we can, together give us just behind the integration MyFilter After instantiation code.

import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import java.io.IOException; @Log4j2 public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { log.info("初始化过滤器"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response); String requestUri = request.getRequestURI(); log.info("请求地址是:"+requestUri); if (requestUri.contains("/addSession") || requestUri.contains("/removeSession") || requestUri.contains("/online") || requestUri.contains("/favicon.ico")) { filterChain.doFilter(servletRequest, response); } else { wrapper.sendRedirect("/online"); } } @Override public void destroy() { //在服务关闭时销毁 log.info("销毁过滤器"); } }

Interceptor

Interceptor Introduction

In Java interceptor to intercept the object is a dynamic action calls and then provide some operations may increase before and after the action execution, you can stop the action before the action performed similar functions and filters, but different standards and implementation.

  • Login authentication: In some applications, it may be verified by the interceptor user's login status, if there is no login or login fails, it will prompt the user with a friendly login page or return, of course, not large-scale projects in this way are adjusted single sign-on system interface to authenticate the user.
  • Record System log: We are common applications, it is common to record the user's request for information, such as requesting ip, method execution time, these records can monitor the system status, so that the system information monitoring, information statistics, calculate PV, performance tuning and so on.
  • General process: All methods there may be returned to the application, this can be achieved using interceptors, each method is omitted redundant duplicate code.

Use interceptor

We need to realize HandlerInterceptor class and override the three methods

  • preHandle: Controoler process is called before the request is the return value  booleantype, if it is trueon to the next step; if returned false, then the proof does not meet the condition to intercept, at the time of failure will not contain any response, then need to call the corresponding responsereturn the corresponding response.
  • postHandler: Controoler processing request in execution is completed, before performing generate views, through ModelAndViewto the view processing, of course, ModelAndViewmay be set to null.
  • afterCompletion: DispatcherServlet after being completely processed the request to call, often used to record time-consuming, it is possible for some resources for processing.
import lombok.extern.log4j.Log4j2;
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; import javax.servlet.http.HttpSession; @Log4j2 @Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("【MyInterceptor】调用了:{}", request.getRequestURI()); request.setAttribute("requestTime", System.currentTimeMillis()); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if (!request.getRequestURI().contains("/online")) { HttpSession session = request.getSession(); String sessionName = (String) session.getAttribute("name"); if ("haixiang".equals(sessionName)) { log.info("【MyInterceptor】当前浏览器存在 session:{}",sessionName); } } } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { long duration = (System.currentTimeMillis() - (Long)request.getAttribute("requestTime")); log.info("【MyInterceptor】[{}]调用耗时:{}ms",request.getRequestURI(), duration); } } 

Monitor

Listeners Introduction

Listeners typically used to monitor the action of sending a Web application object creation, destruction, etc., and make the appropriate treatment to monitor the situation, the number of the most commonly used online, such as website traffic statistics.

Listeners roughly divided into the following categories:

  • ServletContextListener: ServletContext attribute is used to monitor the operation, such as add, modify, delete.
  • HttpSessionListener: Web application used to monitor species Session object, usually for statistical online.
  • ServletRequestListener: attribute to monitor the operation of the Request object.

Use listener

We  HttpSessionListenerused to count the current number of online, ip and other information, in order to avoid concurrency issues we used to count the atomic int.

ServletContext, is a global information space to store its life cycle and Servlet container that is consistent with the server, the server shuts down before destruction. request, a user may have multiple; session, a user selection; servletContext, a common to all users. So, in order to save space, improve efficiency, ServletContext, we should have to put, it is important that all users need to share the security thread is some information. So here we are with a number of online stores ServletContext sessionCountmost appropriate.

We turn next to the current number of online statistics

import lombok.extern.log4j.Log4j2;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.concurrent.atomic.AtomicInteger;

@Log4j2 public class MyHttpSessionListener implements HttpSessionListener { public static AtomicInteger userCount = new AtomicInteger(0); @Override public synchronized void sessionCreated(HttpSessionEvent se) { userCount.getAndIncrement(); se.getSession().getServletContext().setAttribute("sessionCount", userCount.get()); log.info("【在线人数】人数增加为:{}",userCount.get()); //此处可以在ServletContext域对象中为访问量计数,然后传入过滤器的销毁方法 //在销毁方法中调用数据库入库,因为过滤器生命周期与容器一致 } @Override public synchronized void sessionDestroyed(HttpSessionEvent se) { userCount.getAndDecrement(); se.getSession().getServletContext().setAttribute("sessionCount", userCount.get()); log.info("【在线人数】人数减少为:{}",userCount.get()); } } 

Filters, interceptors, listener registration

Examples of the three filter

import com.anqi.tool.sanqi.filter.MyFilter;
import com.anqi.tool.sanqi.interceptor.MyInterceptor;
import com.anqi.tool.sanqi.listener.MyHttpRequestListener;
import com.anqi.tool.sanqi.listener.MyHttpSessionListener;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Autowired MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor); } /** * 注册过滤器 * @return */ @Bean public FilterRegistrationBean filterRegistrationBean(){ FilterRegistrationBean filterRegistration = new FilterRegistrationBean(); filterRegistration.setFilter(new MyFilter()); filterRegistration.addUrlPatterns("/*"); return filterRegistration; } /** * 注册监听器 * @return */ @Bean public ServletListenerRegistrationBean registrationBean(){ ServletListenerRegistrationBean registrationBean = new ServletListenerRegistrationBean(); registrationBean.setListener(new MyHttpRequestListener()); registrationBean.setListener(new MyHttpSessionListener()); return registrationBean; } } 

test

import com.anqi.tool.sanqi.listener.MyHttpSessionListener;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; @RestController public class TestController { @GetMapping("addSession") public String addSession(HttpServletRequest request) { HttpSession session = request.getSession(); session.setAttribute("name", "haixiang"); return "当前在线人数" + session.getServletContext().getAttribute("sessionCount") + "人"; } @GetMapping("removeSession") public String removeSession(HttpServletRequest request) { HttpSession session = request.getSession(); session.invalidate(); return "当前在线人数" + session.getServletContext().getAttribute("sessionCount") + "人"; } @GetMapping("online") public String online() { return "当前在线人数" + MyHttpSessionListener.userCount.get() + "人"; } }

The following is a listener listens for requests

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;

public class MyHttpRequestListener implements ServletRequestListener { @Override public void requestDestroyed(ServletRequestEvent sre) { System.out.println("request 监听器被销毁"); } @Override public void requestInitialized(ServletRequestEvent sre) { HttpServletRequest req = (HttpServletRequest) sre.getServletRequest(); String requestURI = req.getRequestURI(); System.out.println(requestURI+"--"+"被调用"); } }

The difference between the interceptor and filter

1. References

  • JavaEE standard filter is dependent on the Servlet container, the container is also consistent with the life cycle, use of this feature can be destroyed or released resources when data storage.
  • SpringMVC interceptor content is, depending on the web frame, typically used to verify user authority or logging, these functions may also be used instead of AOP.

2. implementation

  • Filter callback function is realized, it can not be injected into the container based bean ioc.
  • Based on the reflected interceptor is achieved, thus the interceptor can be injected in the bean container ioc, e.g. injection Redis business layer to verify that the user has logged.
 



PS: the original link https://www.cnblogs.com/haixiang/p/12000685.html , please indicate the source

filter

Filter Introduction

The English name for the filter Filter, Servlet technology is the most practical technology. As its name suggests, it is in a filter between the client and server resource file filter to help filter out some of us do not meet the requirements of the request, commonly used as Session check to determine user privileges, if it does not set conditions, it will be blocked to a particular address or based on special response.

Use filters

We first need to implement  Filterthe interface and then rewrite it three methods

  • init method: create the current filter in the container when the automatic call
  • destory method: when the destruction of the current filter in the container automatically calls
  • doFilter method: in the specific operation of the filter

We first introduced Maven dependency, which is used to avoid lombok each file to print the log created Logger

        <dependency>
            <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

We first implement the interface, override three methods, we ask for the request contains four to be released, will be redirected to other request interceptor /online, we can, together give us just behind the integration MyFilter After instantiation code.

import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import java.io.IOException; @Log4j2 public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { log.info("初始化过滤器"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response); String requestUri = request.getRequestURI(); log.info("请求地址是:"+requestUri); if (requestUri.contains("/addSession") || requestUri.contains("/removeSession") || requestUri.contains("/online") || requestUri.contains("/favicon.ico")) { filterChain.doFilter(servletRequest, response); } else { wrapper.sendRedirect("/online"); } } @Override public void destroy() { //在服务关闭时销毁 log.info("销毁过滤器"); } }

Interceptor

Interceptor Introduction

In Java interceptor to intercept the object is a dynamic action calls and then provide some operations may increase before and after the action execution, you can stop the action before the action performed similar functions and filters, but different standards and implementation.

  • Login authentication: In some applications, it may be verified by the interceptor user's login status, if there is no login or login fails, it will prompt the user with a friendly login page or return, of course, not large-scale projects in this way are adjusted single sign-on system interface to authenticate the user.
  • Record System log: We are common applications, it is common to record the user's request for information, such as requesting ip, method execution time, these records can monitor the system status, so that the system information monitoring, information statistics, calculate PV, performance tuning and so on.
  • General process: All methods there may be returned to the application, this can be achieved using interceptors, each method is omitted redundant duplicate code.

Use interceptor

We need to realize HandlerInterceptor class and override the three methods

  • preHandle: Controoler process is called before the request is the return value  booleantype, if it is trueon to the next step; if returned false, then the proof does not meet the condition to intercept, at the time of failure will not contain any response, then need to call the corresponding responsereturn the corresponding response.
  • postHandler: Controoler processing request in execution is completed, before performing generate views, through ModelAndViewto the view processing, of course, ModelAndViewmay be set to null.
  • afterCompletion: DispatcherServlet after being completely processed the request to call, often used to record time-consuming, it is possible for some resources for processing.
import lombok.extern.log4j.Log4j2;
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; import javax.servlet.http.HttpSession; @Log4j2 @Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("【MyInterceptor】调用了:{}", request.getRequestURI()); request.setAttribute("requestTime", System.currentTimeMillis()); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if (!request.getRequestURI().contains("/online")) { HttpSession session = request.getSession(); String sessionName = (String) session.getAttribute("name"); if ("haixiang".equals(sessionName)) { log.info("【MyInterceptor】当前浏览器存在 session:{}",sessionName); } } } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { long duration = (System.currentTimeMillis() - (Long)request.getAttribute("requestTime")); log.info("【MyInterceptor】[{}]调用耗时:{}ms",request.getRequestURI(), duration); } } 

Monitor

Listeners Introduction

Listeners typically used to monitor the action of sending a Web application object creation, destruction, etc., and make the appropriate treatment to monitor the situation, the number of the most commonly used online, such as website traffic statistics.

Listeners roughly divided into the following categories:

  • ServletContextListener: ServletContext attribute is used to monitor the operation, such as add, modify, delete.
  • HttpSessionListener: Web application used to monitor species Session object, usually for statistical online.
  • ServletRequestListener: attribute to monitor the operation of the Request object.

Use listener

We  HttpSessionListenerused to count the current number of online, ip and other information, in order to avoid concurrency issues we used to count the atomic int.

ServletContext, is a global information space to store its life cycle and Servlet container that is consistent with the server, the server shuts down before destruction. request, a user may have multiple; session, a user selection; servletContext, a common to all users. So, in order to save space, improve efficiency, ServletContext, we should have to put, it is important that all users need to share the security thread is some information. So here we are with a number of online stores ServletContext sessionCountmost appropriate.

We turn next to the current number of online statistics

import lombok.extern.log4j.Log4j2;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.concurrent.atomic.AtomicInteger;

@Log4j2 public class MyHttpSessionListener implements HttpSessionListener { public static AtomicInteger userCount = new AtomicInteger(0); @Override public synchronized void sessionCreated(HttpSessionEvent se) { userCount.getAndIncrement(); se.getSession().getServletContext().setAttribute("sessionCount", userCount.get()); log.info("【在线人数】人数增加为:{}",userCount.get()); //此处可以在ServletContext域对象中为访问量计数,然后传入过滤器的销毁方法 //在销毁方法中调用数据库入库,因为过滤器生命周期与容器一致 } @Override public synchronized void sessionDestroyed(HttpSessionEvent se) { userCount.getAndDecrement(); se.getSession().getServletContext().setAttribute("sessionCount", userCount.get()); log.info("【在线人数】人数减少为:{}",userCount.get()); } } 

Filters, interceptors, listener registration

Examples of the three filter

import com.anqi.tool.sanqi.filter.MyFilter;
import com.anqi.tool.sanqi.interceptor.MyInterceptor;
import com.anqi.tool.sanqi.listener.MyHttpRequestListener;
import com.anqi.tool.sanqi.listener.MyHttpSessionListener;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Autowired MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor); } /** * 注册过滤器 * @return */ @Bean public FilterRegistrationBean filterRegistrationBean(){ FilterRegistrationBean filterRegistration = new FilterRegistrationBean(); filterRegistration.setFilter(new MyFilter()); filterRegistration.addUrlPatterns("/*"); return filterRegistration; } /** * 注册监听器 * @return */ @Bean public ServletListenerRegistrationBean registrationBean(){ ServletListenerRegistrationBean registrationBean = new ServletListenerRegistrationBean(); registrationBean.setListener(new MyHttpRequestListener()); registrationBean.setListener(new MyHttpSessionListener()); return registrationBean; } } 

test

import com.anqi.tool.sanqi.listener.MyHttpSessionListener;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; @RestController public class TestController { @GetMapping("addSession") public String addSession(HttpServletRequest request) { HttpSession session = request.getSession(); session.setAttribute("name", "haixiang"); return "当前在线人数" + session.getServletContext().getAttribute("sessionCount") + "人"; } @GetMapping("removeSession") public String removeSession(HttpServletRequest request) { HttpSession session = request.getSession(); session.invalidate(); return "当前在线人数" + session.getServletContext().getAttribute("sessionCount") + "人"; } @GetMapping("online") public String online() { return "当前在线人数" + MyHttpSessionListener.userCount.get() + "人"; } }

The following is a listener listens for requests

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;

public class MyHttpRequestListener implements ServletRequestListener { @Override public void requestDestroyed(ServletRequestEvent sre) { System.out.println("request 监听器被销毁"); } @Override public void requestInitialized(ServletRequestEvent sre) { HttpServletRequest req = (HttpServletRequest) sre.getServletRequest(); String requestURI = req.getRequestURI(); System.out.println(requestURI+"--"+"被调用"); } }

The difference between the interceptor and filter

1. References

  • JavaEE standard filter is dependent on the Servlet container, the container is also consistent with the life cycle, use of this feature can be destroyed or released resources when data storage.
  • SpringMVC interceptor content is, depending on the web frame, typically used to verify user authority or logging, these functions may also be used instead of AOP.

2. implementation

  • Filter callback function is realized, it can not be injected into the container based bean ioc.
  • Based on the reflected interceptor is achieved, thus the interceptor can be injected in the bean container ioc, e.g. injection Redis business layer to verify that the user has logged.

Guess you like

Origin www.cnblogs.com/xichji/p/12009241.html