Spring MVC Interceptor
Usually the interceptors used are the way XML is configured. Today, we specially researched the interceptor of the annotated mode.
Configuring the spring environment here is not a detailed introduction. In this paper, we mainly introduce the interceptor based on the annotation method under spring.
First step: Define the Interceptor implementation class
Public classAuthinterceptorextendsHandlerinterceptoradapter {@Override Public BooleanPrehandle (HttpServletRequest request, httpservletresponse response, Object handler)throwsException {if(Handler.getclass (). IsAssignableFrom (Handlermethod.class) {authpassport Authpassport= ((Handlermethod) handler). Getmethodannotation (Authpassport.class); //no claims are required, or the claim does not verify permissions if(Authpassport = =NULL|| Authpassport.validate () = =false) return true; Else{ //here to implement their own authorization to verify the logic, the use of the session to determine whether there are username, if so, then verify through, do not intercept. String username = (string) request.getsession (). getattribute ("username"); if(Username! =NULL)//true if validation returns successfully return true; Else//if validation fails { //back to the login screenResponse.sendredirect (Request.getcontextpath () + "/account/login"); return false; } } } Else return true; }}
Step two: Customize the annotation implementation class and add it to a specific controller that needs to be intercepted.
@Documented @inherited@target (elementtype.method) @Retention (retentionpolicy.runtime) public @Interface authpassport { booleandefaulttrue ;}
Step three: Add a defined interceptor to the Spring MVC interception system.
(1): Add the schema required for the interceptor in the Springmvc configuration file,
HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
(2): After the schema is added, you can declare the interceptor directly using the label:<mvc:interceptors> in the SPRINGMVC configuration file. The Interceptor Declaration configuration file code is as follows:
<mvc:interceptors> <!--If you do not define mvc:mapping path will intercept all URL requests-- class= " Com.demo.web.auth.AuthInterceptor "></bean></mvc:interceptors>
Fourth step: Add custom intercept annotations in the controller's method. You only need to add @authpassport to the specific method.
@AuthPassport @RequestMapping (value={"/index", "/hello"}) public Modelandview index () { new Modelandview (); Modelandview.addobject ("message", "Hello world!" ); Modelandview.setviewname ("index"); return modelandview; }
With the four steps above, the URL can be intercepted in a note-based manner.
Code: HTTP://PAN.BAIDU.COM/S/1SJP5B1Z
Spring Annotation Interceptor Usage Explained