SpringWebFlux中如何使用WebSession持久化数据?

How to use WebSession in Spring WebFlux to persist data?

我正在尝试使用 Spring WebFlux5.0.1 和 Spring boot v2.0 M6 版本开发 Web 应用程序。需求是在session中存储对象,在后续pages/controllers中使用。

控制器

@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 对象,但我没有看到 set/get 属性的方法

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

这是你想做的吗?

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

在我看来,公认的解决方案是不完整的,因为它没有显示整个控制器方法,这里是如何完成的:

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