Spring boot RESTFul API intercept and filter and interceptor, aspect differences

Source: Internet
Author: User
Tags throw exception

Learn about RESTful API interception today

There are about three different ways

First, through the filter this everyone is familiar with it, this is a Java specification of a filter, he will intercept the request. In Springboot, there are generally two ways to configure.

This filter interception does not know which controller you are using or which method you are dealing with.

(1) The first kind of direct write class implements this interface. The code follows this to use the component annotation, when you request the server, he will handle each request.

 PackageCom.nbkj.webFilter;Importorg.springframework.stereotype.Component;Importjavax.servlet.*;Importjava.io.IOException;Importjava.util.Date; @Component Public classTimerfilterImplementsFilter {@Override Public voidInit (Filterconfig filterconfig)throwsservletexception {System.out.println ("Time Filter Init"); } @Override Public voidDoFilter (ServletRequest servletrequest, Servletresponse servletresponse, Filterchain filterchain)throwsIOException, servletexception {System.out.println ("Time filter Start"); LongStartTime =NewDate (). GetTime ();        Filterchain.dofilter (ServletRequest, servletresponse); System.out.println ("Time Filter:" + (NewDate (). GetTime ()-startTime)); System.out.println ("Time Filter Finish"); } @Override Public voiddestroy () {System.out.println ("Time Filter Destroy"); }}

(2) The second type can be configured in Webconfig, which is used in order to use a third-party filter without @compont annotations. The code is as follows

 PackageCom.nbkj.config;ImportCom.nbkj.webFilter.TimerFilter;ImportOrg.springframework.boot.web.servlet.FilterRegistrationBean;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;Importjava.util.ArrayList;Importjava.util.List;/*** Web Configuration * *@authorHSJ * @Configuration This annotation declares that this class is a configuration class * @create 2017-11-11 18:00 **/@Configuration Public classWebconfig {@Bean PublicFilterregistrationbean Timefilter () {Filterregistrationbean Registrationbean=NewFilterregistrationbean (); Timerfilter Timerfilter=NewTimerfilter ();        Registrationbean.setfilter (Timerfilter); List<String> URLs =NewArraylist<>(); Urls.add ("/*");        Registrationbean.seturlpatterns (URLs); returnRegistrationbean; }}

Second, the use of interceptor this kind of thing spring framework itself with the interceptor, code as follows it will handle its own written interceptors, will also intercept the interception of Basicerrorcontroller

You can get the controller to handle and get the processing method but not the specific request parameters.

 PackageCom.nbkj.interceptor;Importorg.springframework.stereotype.Component;ImportOrg.springframework.web.method.HandlerMethod;ImportOrg.springframework.web.servlet.HandlerInterceptor;ImportOrg.springframework.web.servlet.ModelAndView;ImportJavax.persistence.Convert;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjava.util.Date;/*** This is Spring interceptor * *@authorHSJ * @create 2017-11-11 18:16 **/@Component Public classTimeinterceptorImplementsHandlerinterceptor {/*** Before the controller method is processed *@paramHttpServletRequest *@paramHttpServletResponse *@paramHandler *@return     * @throwsException*/@Override Public BooleanPrehandle (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object handler)throwsException {System.out.println ("Prehandle");        System.out.println ((Handlermethod) handler). Getbean (). GetClass (). GetName ());        System.out.println ((Handlermethod) handler). GetMethod (). GetName ()); Httpservletrequest.setattribute ("StartTime",NewDate (). GetTime ()); return false; }    /*** After the controller method is processed * Controller method call does not throw exception call * *@paramHttpServletRequest *@paramHttpServletResponse *@paramO *@paramModelandview *@throwsException*/@Override Public voidPosthandle (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object handler, Modelandview Modelandview)throwsException {System.out.println ("Posthandle"); Long StartTime= (Long) httpservletrequest.getattribute ("StartTime"); System.out.println ("Time Interceptor" + (NewDate (). GetTime ()-startTime)); }    /*** Controller method will be called without throwing exceptions * *@paramHttpServletRequest *@paramHttpServletResponse *@paramO *@paramE *@throwsException*/@Override Public voidAftercompletion (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o, Exception E )throwsException {System.out.println ("Aftercompletion"); Long StartTime= (Long) httpservletrequest.getattribute ("StartTime"); System.out.println ("Time Interceptor" + (NewDate (). GetTime ()-startTime)); System.out.println ("Ex is" +e); }}

 PackageCom.nbkj.config;ImportCom.nbkj.interceptor.TimeInterceptor;ImportCom.nbkj.webFilter.TimerFilter;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.boot.web.servlet.FilterRegistrationBean;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;ImportOrg.springframework.web.servlet.config.annotation.InterceptorRegistry;ImportOrg.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;Importjava.util.ArrayList;Importjava.util.List;/*** Web Configuration * *@authorHSJ * @Configuration This annotation declares that this class is a configuration class * @create 2017-11-11 18:00 **/@Configuration Public classWebconfigextendsWebmvcconfigureradapter {@AutowiredPrivateTimeinterceptor Timeinterceptor; @Override Public voidaddinterceptors (Interceptorregistry registry) {Registry.addinterceptor (timeinterceptor); }    }

Third, the use of aspect slices, the code is as follows

Use surround notification to cut into the class you want to cut in, and intercept it when requested, so you can get the parameters of the blocking method

 PackageCom.nbkj.aspect;ImportOrg.aspectj.lang.ProceedingJoinPoint;ImportOrg.aspectj.lang.annotation.Around;ImportOrg.aspectj.lang.annotation.Aspect;Importorg.springframework.stereotype.Component;Importjava.util.Date;/*** This is a acpect * pointcut * works on those methods * when does it work *@authorHSJ * @create 2017-11-11 20:52 **/@Aspect @component Public classtimeaspect {@Around ("Execution (* com.nbkj.controller.usercontroller.* (..))")     PublicObject Handlecontrollermethod (Proceedingjoinpoint proceedingjoinpoint)throwsthrowable {System.out.println ("Time aspect start"); Object[] args=Proceedingjoinpoint.getargs ();  for(Object Arg:args) {System.out.println (Arg.getclass (). GetName ()); System.out.println ("Arg is" +Arg); }        LongStartTime =NewDate (). GetTime (); Object obj=proceedingjoinpoint.proceed (); System.out.println ("Time aspect" + (NewDate (). GetTime ()-startTime)); System.out.println ("Time Aspect End"); returnobj; }}

Filter: You can get the original HTTP request, but you can't get the information of the controller you requested and the method in the request controller.

Interceptor (Interceptor): You can get the controller and method you requested, but can't get the parameters of the request method.

Slicing (Aspect): You can get the parameters of a method, but you can't get the HTTP request and Response object

Spring boot RESTFul API intercept and filter and interceptor, aspect differences

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.