我正在尝试添加一个过滤器,该过滤器创建一个对象,然后在 Spring Boot 应用程序的 Controller 中使用该对象。
这个想法是将过滤器用作此对象的“集中式”生成器 - 这是特定于请求的并且仅在 Controller 中有用。
我试过使用 HttpServletRequest request.getSession().setAttribute
方法:我可以在 Controller 中访问我的对象,但随后它将(显然)添加到 session 中。
过滤器是这样做的正确方法吗?如果是,我在哪里可以保存过滤器生成的临时对象以供 Controller 使用?
最佳答案
为什么不使用带有 @Scope('request')
的 Bean
@Component
@Scope(value="request", proxyMode= ScopedProxyMode.TARGET_CLASS)
class UserInfo {
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private String password;
}
然后你可以
Autowireed
过滤器和 Controller 中的这个 bean 用于设置和获取数据。此生命周期
UserInfo
bean 仅存在于请求中,因此一旦 http 请求完成,它也会终止实例
关于Spring:如何将对象从过滤器传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35444633/