使用spring自定义注解实现权限访问
1. 首先定义注解类
2. 使用拦截器实现注解功能
3. 配置拦截器
4. 在controller层使用注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Permission {
/**
* 资源key
* */
String value();
}
import com.annotation.demo.annotation.Permission;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PermissionInterceptor implements HandlerInterceptor {
/**
* 处理器处理之前调用
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
//在方法上寻找注解
Permission permission = handlerMethod.getMethodAnnotation(Permission.class);
if (permission == null) {
//在类上寻找注解
permission = handlerMethod.getBeanType().getAnnotation(Permission.class);
}
//如果没有添加权限注解则直接跳过允许访问
if (permission == null) {
return true;
}
//获取注解中的值
String value = permission.value();
if ("admin".equals(value)) {
return true;
}
return false;
}
}
import com.annotation.demo.interceptor.PermissionInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
/**
* 注册自定义拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new PermissionInterceptor()).addPathPatterns("/api/**");
}
}
package com.annotation.demo.controller;
import com.annotation.demo.annotation.Permission;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author : spiderman
* @version : 1.0
* @FileName : com.annotation.demo
* @Description :
* @Create Date : 2022/1/5 00:24
**/
@RestController
public class TestController {
/**
* 权限为admin才能访问
* @return
*/
@RequestMapping("/api/test")
@Permission(value = "admin")
public String test() {
return "hello world";
}
/**
* 权限为test2才能访问
* @return
*/
@RequestMapping("/api/test2")
@Permission(value = "test2")
public String test2() {
return "hello world";
}
}