Implementing Permission Validation in Spring MVC with Custom Annotations
This article explains how to set up permission validation in a Spring MVC project using user‑role‑resource tables, compares three verification approaches, and demonstrates a custom annotation solution with full controller and interceptor code examples.
When using Spring MVC for a project, permission validation is needed.
The database tables are:
User table
Role table
Resource table
Users, roles, and resources have many‑to‑many relationships; validation typically occurs in an interceptor that loops through the user's permissions.
Method 1: Get the request URI and iterate to check permission (tedious)
Method 2: Determine permission based on the handler method
In preHandle , the handler is actually a HandlerMethod (sometimes not). Use instanceof to verify.
Method name can be obtained with h.getMethod().getName() .
RequestMapping annotation value can be obtained with h.getMethodAnnotation(RequestMapping.class) .
This approach is still inconvenient.
Method 3: Custom Annotation
Custom annotation definition:
@Retention(RUNTIME)
@Target(METHOD)
public @interface MyOperation {
String value() default ""; // default empty, name is "value"
}Controller example:
@Controller("testController")
public class TestController {
@MyOperation("User Update") // main point
@RequestMapping("test")
@ResponseBody
public String test(String id) {
return "Hello,2018!" + id;
}
}Interceptor implementation:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Entering interceptor");
if (handler instanceof HandlerMethod) {
HandlerMethod h = (HandlerMethod) handler;
System.out.println("User wants to perform operation: " +
h.getMethodAnnotation(MyOperation.class).value());
// perform permission check here...
}
return HandlerInterceptor.super.preHandle(request, response, handler);
}Adding the annotation on every method is cumbersome; you can place it on the class instead:
@Retention(RUNTIME)
@Target(TYPE)
public @interface MyOperation {
String value() default "";
}
// In interceptor:
MyOperation op = h.getMethod().getDeclaringClass().getAnnotation(MyOperation.class);Alternatively, you can retrieve the RequestMapping directly without creating a custom annotation, but avoid using GetMapping and other shortcut annotations; use RequestMapping instead.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
