【问题标题】:How to use WebSession in Spring WebFlux to persist data?如何在 Spring WebFlux 中使用 WebSession 来持久化数据?
【发布时间】:2018-05-04 12:32:50
【问题描述】:

我正在尝试使用 Spring WebFlux5.0.1 和 Spring boot v2.0 M6 版本开发 Web 应用程序。要求是将对象存储在会话中并在后续页面/控制器中使用它。

控制器

@Controller
public class TestController {

    @RequestMapping("/")
    public Mono<String> testSession(Model model,ServerWebExchange swe){
        Mono<WebSession> session = swe.getSession();
        System.out.println("In testSession "+session);

        model.addAttribute("account", new Account());
        return Mono.just("account");
    }
}

我能够从 ServerWebExchange 获取 Websession 对象,但我没有看到设置/获取属性的方法

需要帮助了解如何在响应式世界中使用 WebSession 对象

【问题讨论】:

  • 请在此处添加您尝试过的任何代码。
  • 请阅读stackoverflow.com/help/how-to-ask,了解如何提问。对于初学者,请解释(并添加代码)您尝试过的内容。

标签: spring spring-webflux


【解决方案1】:

这是你想做的吗?

swe.getSession().map(
    session -> { 
        session.getAttribute("foo"); // GET
        session.getAttributes().put("foo", "bar") // SET
    }
);

【讨论】:

  • 我认为这还不完整,我们可能需要从这里返回一些东西。
  • 另外,我如何才能从 ServerWebExchange 中获取 WebSession 我的意思不是在 lambda 内部,而是作为实例变量
  • 我试过你的代码,但控件没有进入 map()。可能是什么原因
【解决方案2】:

在我看来,接受的解决方案是不完整的,因为它没有显示整个控制器方法,这是它的完成方式:

@PostMapping("/login")
fun doLogin(@ModelAttribute credentials: Credentials, swe: ServerWebExchange): Mono<String> {
    return swe.session.flatMap {
        it.attributes["userId"] = credentials.userId
        "redirect:/globalPosition".toMono()
    }
}

【讨论】:

    猜你喜欢
    • 2021-10-02
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    相关资源
    最近更新 更多