Requirements: The project needs to dynamically modify the request parameters, to assign values to the request parameters according to the current user's permissions, before the parameters enter the controller method, the modification of the request parameters must be completed, and when the controller calls the service layer, the request parameters can be used as conditions to query and modify the data. There are two cases of requesting parameters:
- For users with high privileges, you can use the actual requested parameter values
- For people with only partial permissions, the request parameter values are dynamically modified based on the information bound to the current user
At first, I wanted to implement it through a filter, but it was too cumbersome to serialize and deserialize the request content, and it also required a lot of logical judgment and performance loss. Fortunately, Spring provides AOP face-oriented functionality, which can be implemented with simple code.
First of all, the maven project pom.xml needs to introduce the spring-boot-starter-aop package, as follows:
Once the package is introduced, we can use the AOP feature, through@Aspectannotation.
Aspect supports 5 types of notification annotations:
@Before: Pre-notification, which is executed before the method is executed
@After: Post-notification, executed after the method is executed
@AfterRunning: Returns a notification, which is executed after the method returns a result
@AfterThrowing: Exception notification, after the method throws an exception
@Around: Wraparound notifications, around method execution
Create a Request.java generic request wrapper class:
Create a new UserInfo.java request specific data class:
If the current request header has an appid, the value of the request parameter appId will be modified, otherwise, the request parameter will not be modified, the code is as follows:
Create a new HomeController controller and add an interface with a request parameter containing Request<UserInfo>, the code is as follows:
In the case of testing without the appId request header, the request parameter appId is the actual value and has not been modified, as shown in the following figure:
If you try to add the appId request header, you can see that the appId request parameter has been successfully modified, as shown in the following figure:
Finally, attach the source code:The hyperlink login is visible.
|