简述sprinboot拦截器使用.
定义一个拦截器处理类
简单来说就是你将访问拦截下来要干什么
比如验证身份或者 登录状态,权限等
实在只想看一下拦截效果,不想实现其他功能就直接写一个控制台输出也行
示例:
public class AppIdInterceptor implements HandlerInterceptor {
private final RedisTemplate<String, String> redisTemplate;
private static final Logger logger = LoggerFactory.getLogger(CheckHumanService.class);
public AppIdInterceptor(RedisTemplate<String, String> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String appIdHeader = request.getHeader("appId");
if (appIdHeader == null) {
MessageResponse<String> errorResponse = MessageResponse.error(400, "Missing appId in headers.");
sendResponse(response, 400, errorResponse);
logger.error("Missing appId in headers.(请设置header appId = asdfghjkl43279087274)");
return false;
}
String appIdFromRedis = redisTemplate.opsForValue().get("appId");
if (!appIdHeader.equals(appIdFromRedis)) {
MessageResponse<String> errorResponse = MessageResponse.error(513, "非法访问!");
sendResponse(response, 513, errorResponse);
logger.error("appId错误(请设置header appId = asdfghjkl43279087274)");
return false;
}
return true;
}
// Helper method to send the response
private void sendResponse(HttpServletResponse response, int statusCode, MessageResponse<?> responseData) throws IOException {
response.setStatus(statusCode);
response.setContentType("application/json;charset=UTF-8");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(response.getWriter(), responseData);
}
}
在这个简单的示例中定义了拦截处理的方法:(验证header中的appId是否符合我的预先设定)
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
这个也是代码核心
需要一个包含这些参数的方法,处理拦截目的
(HttpServletRequest request, HttpServletResponse response, Object handler)
配置拦截器
接着刚刚的拦截器进行配置:
示例:
@Configuration
public class WebConfig implements WebMvcConfigurer {
private final RedisTemplate<String, String> redisTemplate;
public WebConfig(RedisTemplate<String, String> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Autowired
public AppIdInterceptor getAppIdInterceptor(){
return new AppIdInterceptor(redisTemplate);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注册拦截器
registry.addInterceptor(this.getAppIdInterceptor()).addPathPatterns("/**");
}
}
代码核心是你需要定义一个WebConfig类(必须使用@Configuration注解)实现WebMvcConfigurer,再实现配置方法addInterceptors配置拦截器
registry.addInterceptor(这里需要一个你定义的拦截器的实体类).addPathPatterns("这里填写你想要拦截的路径");
其他都是为了添加实体类所定义的
到这里拦截器就配置好了
启动服务就可以查看拦截效果
本文由 mdnice 多平台发布