Spring:如何将对象从过滤器传递到 Controller

标签 spring spring-boot

我正在尝试添加一个过滤器,该过滤器创建一个对象,然后在 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/

相关文章:

java - @Component Hibernate 类

java - 是否可以将 Spring Security 的 AOP 与 Java Security Manager 合并?

Spring Data Rest - PATCH Postgres jsonb 字段

Spring 4 STOMP Websockets - 如何实现多 channel

java - 具有不同实体错误的 JPA 托管映射

java - 反序列化 json 时从 JsonArray 中排除 NULL

java - Spring Activity 将于元旦起火

java - hibernate 二级缓存: Update cached collection on creating of entity in oneToMany relation

java - 如何基于@Profile 向 spring-security 添加过滤器?

java - 复杂 REST 请求对象中的默认值