spring method interceptor MethodInterceptor

Use the spring method interceptor MethodInterceptor to implement permission control. MethodInterceptor can use wildcards and is based on annotations.

The simple example code is as follows:

1. Define the class Java code that needs to be intercepted


Collection code

    public class LoginAction{ 
        
        //No permission limit 
        @RequestMapping(value = "/login") 
        public void login(HttpServletRequest req, HttpServletResponse res) { 
               //Login function . 
       } 
     
       //You can access 
       @LoginMethod  after login is complete
       @RequestMapping(value = "/userList") 
        public void userList(HttpServletRequest req, HttpServletResponse res) { 
               //Get the user list 
       } 
     
    } 

Note that the @LoginMethod above is my custom





2. Define the LoginMethod annotation
Java code Collection code

    @Target(ElementType.METHOD) 
    @Retention(RetentionPolicy.RUNTIME) 
    public @interface LoginMethod { 
        
    } 

3. Define MethodInterceptor interceptor
Java code Collection code

    public class SystemMethodInterceptor implements MethodInterceptor { 
        @Override 
        public Object invoke(MethodInvocation methodInvocation) throws Throwable {        
            Method method = methodInvocation.getMethod();    
            if(method.isAnnotationPresent(LoginMethod.class)){//Added @LoginMethod annotation, intercepted 
                 User user = sessionUtil.getCurrUser(); 
                 if(user == null){ //Not logged 
                     in //proceed method is not called, method is intercepted 
                     return null; 
                 }else{ 
                     return methodInvocation.proceed();//If the method is not called, the intercepted method will not be executed 
                 } 
            }else{ 
                return methodInvocation.proceed(); 
            } 
        } 
    } 



4. Collection of configuration text
Xml code Code

    <bean id="systemMethodInterceptor" class="com.tzz.interceptor.SystemMethodInterceptor" > 
    </bean> 
    <aop:config>  
    <!--pointcut-->  
     <aop:pointcut id="methodPoint" expression=" execution(* com.tzz.controllor.web.*.*(..)) "/><!--Use custom interceptor at this pointcut-->  
    <aop:advisor pointcut-ref="methodPoint" advice-ref="systemMethodInterceptor"/> 
    </aop:config>  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326486699&siteId=291194637