java之拦截器的配置

来源:互联网 发布:淘宝定做衣服 编辑:程序博客网 时间:2024/06/05 00:10

1.场景还原

      近期的项目中有很多地方要用到拦截器,比如权限管理,在访问该controller之前先进行对其拦截一把,如果满足权限要求则放行,不满足则抛出无权限异常。

2.实现方案

①定义一个权限访问接口

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface AuthCode {    /**     * 1)纯操作码,如:query     * @return     */    String[] value() default {};}
 ②在controller上面申明权限

/** * 获取未维护记录的消息列表 */@AuthCode({"company.query","company.add"})@RequestMapping(value = "/calculateKpi", produces = "application/json;charset=utf-8")public String calculateKpi(){   LogUtil.info(logger, "获取未维护记录的消息列表=========start");   List<KpiEx> list = rtgCategoryService.calculateKpi();   LogUtil.info(logger, "获取未维护记录的消息列表=========end"+list);   Map<String,List<KpiEx>> map= new HashMap<>();   for (int i =0;i<list.size();i++){      Float respEffective = list.get(i).getRespTime()/list.get(i).getRespSetTime();      Float dealEffective = list.get(i).getDealTime()/list.get(i).getDealSetTime();      Float recoEffective = list.get(i).getRecoTime()/list.get(i).getRecoSetTime();      Float generalEffective = respEffective*dealEffective*recoEffective;      if(respEffective != null) list.get(i).setRespEffective(respEffective);      if(dealEffective != null) list.get(i).setDealEffective(dealEffective);      if(recoEffective != null) list.get(i).setRecoEffective(recoEffective);      if(generalEffective != null) list.get(i).setGenerateEffective(generalEffective);   }   map.put("list", list);   return success(map);}
 ③然后就进入真正拦截器类了

public class AuthInterceptor extends HandlerInterceptorAdapter {    @Autowired    private IAuthService authService;    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        System.out.println(handler.getClass());        HandlerMethod handlerMethod = (HandlerMethod) handler;        AuthCode _authCode = handlerMethod.getMethodAnnotation(AuthCode.class);        //不需要权限控制直接放行        if (_authCode == null) {            return true;        }        //在实际项目中需要在登录的时候就获取并存在缓存中        List<String> authCodesOfUsers = authService.getAuthCodesOfUsers(1);        System.out.print(authCodesOfUsers);        List<String> currAuthCode = new ArrayList<String>();        if (_authCode.value() != null && _authCode.value().length > 0) {            currAuthCode = Arrays.asList(_authCode.value());        } else {            //如果没有设置具体的authCode,则默认使用方法名匹配            currAuthCode.add(handlerMethod.getMethod().getName());        }        //遍历鉴权        boolean hasAuth = false;        for (String authCode : currAuthCode) {            if (authCodesOfUsers.contains(authCode)){                hasAuth = true;                break;            }        }        //若没权限,则抛出权限异常        if (!hasAuth) {            String message = GlobalErrorCode.UNAUTHORIZED.getError();            throw new BizException(GlobalErrorCode.UNAUTHORIZED,message);        } else {            return true;        }    }}
 ④在spring-web中配置拦截器

<!--配置拦截器, 多个拦截器,顺序执行 --><mvc:interceptors>    <mvc:interceptor>        <!-- 匹配的是url路径, 如果不配置或/**,将拦截所有的Controller -->        <mvc:mapping path="/**"/>        <bean class="com.cckj.util.auth.AuthInterceptor"></bean>    </mvc:interceptor>    <!-- 当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandleafterCompletion方法 --></mvc:interceptors>
如果在第④ 步中查询的权限中有company.query或者company.add其中任意一个,则拦截器放行,一个都不包含的话,抛无权限异常。

⑤获取权限的接口

public interface IAuthService {   // List<AuthAction> getActionsOfUsers(long uid);    /**     * 获取权限authCode集合;元素为AuthActionmodule + "." + code 组合;保证唯一性     * @param uid     * @return     */    List<String> getAuthCodesOfUsers(long uid);}
⑥权限实现类

@Service("IAuthService")public class AuthServiceImpl implements IAuthService {   @Autowired    UserService userService;    @Override    public List<String> getAuthCodesOfUsers(long uid) {        List<AuthEx> list = userService.selectUserofActionById(uid);        ArrayList<String> authList = new ArrayList<>();        for(int i=0;i<list.size();i++){            authList.add(list.get(i).getModule()+"."+list.get(i).getActionCode());        }        return authList;    }}
 ⑦对应mapper

<!--通过userId得到用户的权限控制集合--> <select id="selectUserofActionById" parameterType="long" resultType="com.cckj.bean.auth.AuthEx" > select distinct u.id,s.position_title,a.module,a.action_code from auth_action a inner join auth_control c on c.action_id = a.id inner join user u on c.user_id = u.id inner join staff s on u.staff_id = s.id where u.id=#{userId} </select>
好了,今天拦截器就到此为止了,我是张星,欢迎您的关注,后期更精彩。


原创粉丝点击