Springboot Series Tutorial 08: Use of interceptors (interceptor)

Source: Internet
Author: User

Interceptors Intercprot and filter filters actually act like

When I first approached Java using STRUTS2, it was all filter

Later, SPRINGMVC, use Interceptor.

Not too concerned about the difference, anyway, is the role of inspection,

READ carefully the difference between the filter and the Interceptor (Interceptor) and understand a lot

The most important thing to remember is their order of execution: first filter and then interceptor

Pre--action-interception-after interception-after filtering

After understanding the above information, this article speaks about the use of interceptor

The interceptor of your own definition need to inherit handlerinterceptor and implement the corresponding method Prehandle Posthandle to implement interception function.

Also need to be registered according to interception rules

Examples are as follows:

Package Com.xiao.config;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.annotation.Bean; Import Org.springframework.context.annotation.configuration;import Org.springframework.data.redis.core.stringredistemplate;import Org.springframework.util.stringutils;import Org.springframework.web.servlet.handlerinterceptor;import Org.springframework.web.servlet.modelandview;import Org.springframework.web.servlet.config.annotation.interceptorregistry;import Org.springframework.web.servlet.config.annotation.webmvcconfigureradapter;import Com.alibaba.fastjson.JSON; Import Com.xiao.common.result.error;import Com.xiao.common.result.Result; @Configurationpublic class Interceptorconfig extends Webmvcconfigureradapter {@Bean public interfaceauthcheckinterceptor Getinterfaceauthcheck Interceptor () {RetuRN new Interfaceauthcheckinterceptor (); } @Override public void Addinterceptors (Interceptorregistry registry) {//Multiple interceptors form an interceptor chain//Addpathpat Terns is used to add interception rules//Excludepathpatterns User exclusion interception registry.addinterceptor (Getinterfaceauthcheckinterceptor ()). Add        Pathpatterns ("/api/**");        Registry.addinterceptor (New Interfaceauthcheckinterceptor ()). Addpathpatterns ("/api/**");    If interceptor is not injected into Redis or other projects can be directly new, otherwise please use the above method Super.addinterceptors (registry); }/** * Micro-service Interface access key verification * @author Xiaochangwei * * * */class Interfaceauthcheckinterceptor implements        Handlerinterceptor {private Logger Logger = Loggerfactory.getlogger (GetClass ());        @Autowired stringredistemplate stringredistemplate; @Override public void Aftercompletion (HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception Arg 3) throws Exception {} @Override public void POsthandle (HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Modelandview arg3) throws Excepti On {} @Override the public boolean prehandle (HttpServletRequest request, httpservletresponse response, O            Bject obj) throws Exception {String key = Request.getparameter ("key");                if (Stringutils.isempty (key)) {Response.setcontenttype ("application/json;charset=utf-8"); Response.getwriter (). Write (Json.tojsonstring (new Result (Error.INCOMPLETE_API_AUTHEN_INFO.getCode (),                Error.INCOMPLETE_API_AUTHEN_INFO.getMessage ())));            return false;                } else {logger.info ("Test Redis import:" + Stringredistemplate.opsforvalue (). Get (key));            TODO validation logic return true; }        }    }}

It is important to note the difference in registration

Registry.addinterceptor (Getinterfaceauthcheckinterceptor ()). Addpathpatterns ("/api/**"); This way, no matter what the situation can be

Registry.addinterceptor (New Interfaceauthcheckinterceptor ()). Addpathpatterns ("/api/**"); In this case, No other content can be injected into the custom interceptor, such as Redis or other service, if you want to inject it, you must use this method

Springboot Series Tutorial 08: Use of interceptors (interceptor)

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.