# 4.3 Before

The Before annotation is used to configure interceptors. This annotation can configure Class and Method level interceptors. Here's a code example:

// Configures a Class-level interceptor, which will intercept all methods in this class
@Before(AaaInter.class)
public class BlogController extends Controller {
 
  // Configures multiple Method-level interceptors, only intercepting this method
  @Before({BbbInter.class, CccInter.class})
  public void index() {
  }
 
  // No Method-level interceptor configured, but it will be intercepted by the Class-level interceptor AaaInter
  public void show() {
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

As shown in the code above, the Before annotation can configure interceptors at the Class and Method levels. The former intercepts all methods in this class, and the latter only intercepts this method. Additionally, Before can configure multiple interceptors at once. You just need to separate multiple interceptors with commas inside curly braces.

In addition to Class and Method level interceptors, JFinal also supports global interceptors and Routes interceptors. Global interceptors are divided into global control layer interceptors and global business layer interceptors. The former intercepts all Action methods in the control layer, while the latter intercepts all methods in the business layer.

Global interceptors need to be configured in YourJFinalConfig. Here's a configuration example:

public class YourJFinalConfig extends JFinalConfig {
   public void configInterceptor(Interceptors me) {
      // Add a global control layer interceptor
      me.addGlobalActionInterceptor(new GlobalActionInterceptor());
  
      // Add a global business layer interceptor
      me.addGlobalServiceInterceptor(new GlobalServiceInterceptor());
  
      // A method retained for backward compatibility; its function is exactly the same as addGlobalActionInterceptor
      me.add(new GlobalActionInterceptor());
   }
}
1
2
3
4
5
6
7
8
9
10
11
12

When a Method is intercepted by multiple level interceptors, the order of execution for each level is as follows: Global, Routes, Class, Method. If there are multiple interceptors at the same level, the order of execution within the same level is: those configured earlier execute first.

Last Updated: 9/17/2023, 6:05:19 AM