java拦截器实现

java拦截器实现

package com.xdbigdata.dataAlarm.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.xdbigdata.dataAlarm.model.domain.Role;
import com.xdbigdata.dataAlarm.model.dto.RoleAndInfoDto;
import com.xdbigdata.framework.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description Please describe the role of this class.
 * @Author jg
 * @Date 2020/7/20 15:15
 * @Version 1.0
 */
@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        RoleAndInfoDto roleAndInfoDto = JSONObject.parseObject((String) request.getSession().getAttribute("sessionUser"), RoleAndInfoDto.class);
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        String uri = request.getRequestURI();
        if (uri.matches(".*/static/.+\\..+$")) {
            log.debug("url={}, 为静态资源, 不拦截.", uri);
            return true;
        }
        //不拦截swagger的请求
        if (uri.contains("swagger-") || uri.contains("api-docs") || uri.contains("favicon")) {
            log.debug("不拦截swagger的请求", uri);
            return true;
        }
        if (Objects.isNull(roleAndInfoDto)) {
            throw new BaseException("登录已失效");
        }
        log.debug("run Access Filter roleAndInfoDto --------------> " + roleAndInfoDto.getSn());
        List<String> roleNames = roleAndInfoDto.getRoleList().stream().map(Role::getName).collect(Collectors.toList());
       /* if (Objects.isNull(roleAndInfoDto) || roleNames.contains("学生")) {
            throw new LoginException("当前用工单位无操作权限");
        }*/
        return true;
    }
}
上一篇:Blazor 获取当前的 Url 链接


下一篇:Nginx try_files