Spring MVC Interceptor

Source: Internet
Author: User
Tags stringbuffer

Configuration:

Configure in the MVC configuration file Dispatcher-servlet:

<mvc:interceptors>    <!--all the definitions in this bean will intercept: -    <!--<bean></bean> -    <Mvc:interceptor>        <!--defined here will intercept the specified request URL -        <mvc:mappingPath= "/manage/**"/>        <Beanclass= "Cn.it.controller.common.interceptor.AuthorityInterceptor"/>//To create this interceptor</Mvc:interceptor></mvc:interceptors>

where <mvc:mapping path= ""/>
/** represents all paths and sub-paths inside
/* Indicates all paths under the current path, with no sub-paths
/represents a request for the Web project's root directory.

Cases:
<!--manage/a.do/manage/*-->
<!--manage/b.do/manage/*-->
<!--manage/product/save.do/manage/**-->
<!--manage/order/detail.do/manage/**-->

Under the corresponding package build class: Authorityinterceptor, and Implement Interface Handlerinterceptor.
Will implement three methods: Prehandle, Posthandle, Aftercompletion. This class is entered when the request is matched to a path in the configuration file. Executes the Prehandle method first, then executes the controller corresponding interface, executes the posthandle, and finally executes the aftercompletion. If the Prehandle method returns false, the controller's corresponding interface is no longer executed.

     Public BooleanPrehandle (HttpServletRequest request, httpservletresponse response, Object handler)throwsException {log.info ("Prehandle"); //method name in the controller in the requestHandlermethod Handlermethod =(Handlermethod) handler; //parsing HandlermethodString methodName = Handlermethod.getmethod (). GetName ();//get the name of the method that corresponds to the request in Contoller. String className = Handlermethod.getbean (). GetClass (). Getsimplename ();//gets the simple class name of the controller that corresponds to the request.        If you have the same name under a different package, take the full name and use it for differentiation. //parse parameters, specific parameters key and what value is, we print the logStringBuffer Requestparambuffer =NewStringBuffer (); Map Parammap= Request.getparametermap ();//get the parameter name and parameter value for one by one of the parameters. Iterator it =Parammap.entryset (). iterator ();  while(It.hasnext ()) {Map.entry Entry=(Map.entry) it.next (); String Mapkey=(String) Entry.getkey (); String Mapvalue= Stringutils.empty;//Stringutils.empty is an empty string: ""//request This parameter of the map, inside the value returned is a string[]Object obj = Entry.getvalue ();//returns a string array, which is actually the value of the parameter.             if(objinstanceofstring[]) {string[] STRs=(string[]) obj; Mapvalue= Arrays.tostring (STRs);//turns into a string. } requestparambuffer.append (Mapkey). Append ("="). Append (Mapvalue);//The end result is a string, such as Username=[admin]password=[admin]        }        if(Stringutils.equals (ClassName, "Usermanagecontroller") && stringutils.equals (methodName, "login") {//determine the login operation based on the method name and class name let it go. Resolves an interception login loop. Log.info ("Permission blocker intercepts to request, classname:{},methodname:{}", Classname,methodname); //if it is to intercept the login request, do not print parameters, because the parameters have a password, all will print to the log, to prevent the log leaks            return true;//let's go. } log.info ("Permission blocker intercepts to request, classname:{},methodname:{},param:{}", classname,methodname,requestparambuffer.tostring ()); User User=NULL; String Logintoken= Cookieutil.readlogintoken (request);//get Logintoken from the request.        if(Stringutils.isnotempty (Logintoken)) {String userjsonstr= Redisshardedpoolutil.get (Logintoken);//get the user string from Redis based on Logintokenuser = Jsonutil.string2obj (userjsonstr,user.class);//turn user strings into objects        }        if(User = =NULL|| (User.getrole (). Intvalue ()! = Const.Role.ROLE_ADMIN)) {//If the user is empty or not an administrator. //returns False. The method in the controller is not calledResponse.reset ();//here to add reset, otherwise reported exception getwriter () have already been called for this response.Response.setcharacterencoding ("UTF-8");//because of the SPRINGMVC return process, so here to set the code, otherwise it will be garbled. Response.setcontenttype ("Application/json;charset=utf-8");//this is to set the type of the return value because it is all a JSON interface. PrintWriter out =Response.getwriter (); Out.print (jsonutil.obj2string (Serverresponse.createbyerrormessage ("Interceptor interception, user not logged in or not authorized. ")));Out.flush ();//clears the data in the stream. Out.close ();//Geelynote here to close            return false; }        return true; }

To resolve an interception login loop:

Scenario One: Relatively simple: exclude in configuration.

    <mvc:interceptors>        <Mvc:interceptor>            <mvc:mappingPath= "/manage/**"/>            <mvc:exclude-mappingPath= "/manage/user/login.do"/>            <Beanclass= "Com.mmall.controller.common.interceptor.AuthorityInterceptor"/>        </Mvc:interceptor>    </mvc:interceptors>

Scenario Two: More flexible: judging in interceptors.

        if (Stringutils.equals (ClassName, "Usermanagecontroller") && stringutils.equals (methodName, "login") {// The login operation is determined by the method name and the class name. Resolves an interception login loop.             log.info ("permission blocker intercepts to request, classname:{},methodname:{}", classname,methodname);             // if it is to intercept the login request, do not print parameters, because the parameters have a password, all will print to the log, to prevent the log leaks            return true; // let's go.         }

Spring MVC 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.