拦截器实现拦截到人员的id

WebConfig.WebConfig(配置拦截器)

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public CrewInterceptor crewInterceptor() {
        return new CrewInterceptor();
    }

    /*@Autowired
    private CrewInterceptor crewInterceptor;*/

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(crewInterceptor())
                .addPathPatterns("/**"); // 拦截所有路径
    }
}

Interceptor.CrewInterceptor(创建拦截器)

public class CrewInterceptor implements HandlerInterceptor {

    @Autowired
    private CrewMapper crewMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //
        int id=request.getIntHeader("X-Crew-ID");
        try {
            if(crewMapper.selectById(id).getType() >= 4 && crewMapper.selectById(id).getType() <= 0){
                throw new Exception("权限位置,人员信息错误");
            }
        }
        catch (Exception e){
            response.setStatus(401);
            return false;
        }

        LocalStrorageUtil.set(id);
        return true;
    }
}

util.LocalStorageUtil(实用工具)

public class LocalStrorageUtil {

    //提供ThreadLocal对象
    private static ThreadLocal threadLocal = new ThreadLocal();

    public static Object get(){
        return threadLocal.get();
    }

    public static void set(Object o){
        threadLocal.set(o);
    }

    public static void remove(){
        threadLocal.remove();
    }
}

具体例子实现

@Autowired
private TaskService taskService;
 //*发布任务*//

直接使用请求Param Inter issueId
/*@PostMapping("/release")
public Result release(@RequestParam Integer issueId, @RequestBody TaskDto taskDto){
    log.info("id为:{}的人员发布了id为{}的任务",issueId,taskDto.getId());
    taskService.release(issueId,taskDto);
    return Result.success();
}*/

    
拦截器拦截请求体X-Crew-ID,使用工具类LocalStrorageUtil获取到issueId
@PostMapping("/release")
public Result release(@RequestBody TaskDto taskDto){
    log.info("id为:{}的人员发布了id为{}的任务", LocalStrorageUtil.get(),taskDto.getId());
    System.out.println(LocalStrorageUtil.get());
    int issueId= (int) LocalStrorageUtil.get();
    System.out.println(issueId);
    taskService.release(issueId,taskDto);
    return Result.success();
}

具体拦截器和Jwt令牌代码:

https://blog.csdn.net/2301_79890818/article/details/142701328

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值