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