1.在数据库中创建3张表格
1.admin:用户表
2.role:权限表
3.admin_role:中间表(字段是两个表的主键)
2.自定义注解:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;/*** 注解-用于设置访问的权限人物*/
@Retention(RetentionPolicy.RUNTIME)//表示方法运行时自定义的注解起作用
public @interface Permission {String[] role();
}
3.拦截器 PermissionInterceptor.java
package com.itxiaobai.interceptor;
import com.itxiaobai.annotation.Permission;
import com.itxiaobai.entity.Admin;
import com.itxiaobai.service.AdminService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class PermissionInterceptor implements HandlerInterceptor {
/**
* Object handler"表示访问这个权限的方法
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Autowired
AdminService adminService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//判断有没有登录
Admin admin = (Admin) request.getSession().getAttribute("admin");
if (admin==null){
return false;
}
HandlerMethod method = (HandlerMethod) handler;
//isAnnotationPresent"判断此方法有没有注解
boolean present = method.getMethod().isAnnotationPresent(Permission.class);
//如果方法上没有注解-放行
if (!present){
return true;
}else {
if (admin.getRoles()==null){
admin.setRoles(adminService.selectRolesById(admin.getAdminId()));
}
//通过id获取用户的权限
List<String> roleList = admin.getRoles();
//如果有注解获取方法上的注解的注解内的属性值
String[] roles = method.getMethod().getAnnotation(Permission.class).role();
//通过方法获得两个方法的交集
Collection<String> intersection = CollectionUtils.intersection(roleList, Arrays.asList(roles));
//判断是否有交集
if (intersection.size()>0){
return true;
}else {
return false;
}
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}