Spring boot - 将参数从拦截器传递给控制器​​中的方法

Uli*_* CT 11 spring spring-mvc interceptor spring-boot

出于学习目的,我制作了一个自定义身份验证系统,我通过Authorization标头将令牌从客户端传递到服务器。

在服务器端,我想知道是否可以在拦截器中创建,在请求到达控制器中的方法之前,一个 User 对象,以来自令牌的电子邮件作为属性,然后将此用户对象传递给我需要的每一个请求。

这就是我想得到的,例如:

@RestController
public class HelloController {

    @RequestMapping("/")
    public String index(final User user) {
        return user.getEmail();
    }

}

public class User {
    private String email;
}
Run Code Online (Sandbox Code Playgroud)

其中user是我使用请求Authorization标头在预拦截器中创建的对象,然后我可以传递或不传递给RestController.

这可能吗?

xen*_*ros 7

推荐方案

我将创建一个@Beanwith@Scope请求,该请求将持有用户,然后将适当的实体放入该持有者中,然后从该持有者中取出该方法。

@Component
@Scope("request")
public class CurrentUser {
    private User currentUser;

    public User getCurrentUser() {
        return currentUser;
    }

    public void setCurrentUser(User currentUser) {
        this.currentUser = currentUser;
    }
}
Run Code Online (Sandbox Code Playgroud)

进而

@Component
public class MyInterceptor implements HandlerInterceptor {

   private CurrentUser currentUser;

   @Autowired
   MyInterceptor(CurrentUser currentUser) {
       this.currentUser = currentUser;
   }

   @Override
   public boolean preHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      this.currentUser.setCurrentUser(new User("whatever"));
      return true;
   }
}
Run Code Online (Sandbox Code Playgroud)

并在控制器中

@RestController
public class HelloController {

    private CurrentUser currentUser;

    @Autowired
    HelloController(CurrentUser currentUser) {
        this.currentUser = currentUser;
    }

    @RequestMapping("/")
    public String index() {
        return currentUser.getCurrentUser().getEmail();
    }

}
Run Code Online (Sandbox Code Playgroud)

替代方案

如果您想要的对象只包含一个字段,您可以欺骗它并将该字段添加到HttpServletRequest参数中,然后就可以看到神奇的发生。

@Component
public class MyInterceptor implements HandlerInterceptor {
   @Override
   public boolean preHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      //TRY ONE AT THE TIME: email OR user
      //BOTH SHOULD WORK BUT SEPARATELY OF COURSE
      request.setAttribute("email", "login@domain.com");
      request.setAttribute("user", new User("login@domain.com"));
      return true;
   }
}
Run Code Online (Sandbox Code Playgroud)