标签:return 自定义 Permission spring annotation 注解 import public
使用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";
}
}
标签:return,自定义,Permission,spring,annotation,注解,import,public 来源: https://www.cnblogs.com/javaplus/p/15773451.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。