Java中如何向自定义拦截器preHandle方法传参?是否可从客户端/测试类传参?
Spring MVC拦截器传参解决方案
1. 向preHandle方法传递参数实现校验逻辑
有两种常用实现方案:
- 方案1:通过
HttpServletRequest属性透传参数
任何能拿到当前请求HttpServletRequest对象的位置,都可以通过setAttribute()方法写入自定义参数,拦截器内直接读取即可:
拦截器内读取示例:// 业务代码中写入参数(如Controller层、过滤器等) request.setAttribute("checkRule", "adminOnly");@Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 读取自定义参数 String checkRule = (String) request.getAttribute("checkRule"); // 执行自定义校验逻辑 if("adminOnly".equals(checkRule)){ // 管理员权限校验逻辑 } return true; } } - 方案2:通过接口注解传递配置参数
给需要特殊校验的Controller接口添加自定义注解,把校验参数写在注解中,拦截器通过handler参数读取注解配置:
首先定义自定义注解:
拦截器内读取注解参数:@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface AccessCheck { String role() default "common"; }
使用时直接给Controller接口加注解即可:@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(handler instanceof HandlerMethod){ HandlerMethod handlerMethod = (HandlerMethod) handler; AccessCheck accessCheck = handlerMethod.getMethodAnnotation(AccessCheck.class); if(accessCheck != null){ // 拿到注解中配置的参数 String needRole = accessCheck.role(); // 执行对应校验逻辑 } } return true; }@AccessCheck(role = "admin") @GetMapping("/admin/list") public List<User> getAdminList(){ // 业务逻辑 }
2. 从客户端/测试类向拦截器传递参数
- 客户端传参:直接把参数放在请求头、URL请求参数、请求体中即可,拦截器从
HttpServletRequest中读取对应值:
比如客户端把校验标识放在请求头X-Check-Role中,拦截器读取方式:
普通GET/POST请求参数直接用String role = request.getHeader("X-Check-Role");request.getParameter("参数名")读取即可。 - 测试类传参:以MockMvc单元测试为例,构造请求时直接添加对应请求头/参数即可:
如果是直接测试拦截器类,直接mockmockMvc.perform(MockMvcRequestBuilders.get("/admin/list") .header("X-Check-Role", "admin") .param("testParam", "testValue")) .andExpect(status().isOk());HttpServletRequest对象调用setAttribute写入参数即可。
内容的提问来源于stack exchange,提问作者sr123
相关产品推荐
相关产品推荐

