java - Webflux Reactive 对象在渲染 Thymeleaf View 之前未解析

标签 java thymeleaf spring-webflux

当我尝试在 Thymeleaf 中渲染 View 时,出现错误 由以下原因引起:org.springframework.expression.spel.SpelEvaluationException: EL1008E: 在“reactor”类型的对象上找不到属性或字段“currentTemperature”。 core.publisher.MonoMapFuseable' - 可能不公开或无效?

Spring WebFlux 文档指出“具有响应式类型包装器的模型属性将解析为其实际值”,但是将 Mono<> 作为模型传递给 View 会出现上述错误。

  @RequestMapping(path = "/")
  @GetMapping
  public String home(Model model) {
    Mono<ThermostatState> thermostatState = thermostatClient.fetchThermostatState();
    model.addAttribute("thermostatState", thermostatState);
    return "home";
  }

阻止 Mono<> 并展开内部值会使模板呈现不变,但有点消除了使用响应式(Reactive)库的意义。

  @RequestMapping(path = "/")
  @GetMapping
  public String home(Model model) {
    Mono<ThermostatState> thermostatState = thermostatClient.fetchThermostatState();
    ThermostatState unwrappedState = thermostatState.block();
    model.addAttribute("thermostatState", unwrappedState);
    return "home";
  }

该项目完全依赖于 spring starter 依赖项,并且没有显式的配置类。

最佳答案

嗨,我也是 Spring 和响应式编程的新手;但我认为,可以这样处理。

 @RequestMapping(path = "/")
 @GetMapping
 public Mono<String> home(Model model) {
    return thermostatClient.fetchThermostatState()
      .map(thermostatState -> {
         model.addAttribute("thermostatState", thermostatState);
         return "home";
      });
 }

关于java - Webflux Reactive 对象在渲染 Thymeleaf View 之前未解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61470200/

相关文章:

spring-boot - 缺少 Content-Length header 使用 WebClient 发送 POST 请求(SpringBoot 2.0.2.RELEASE)

java - 为什么 javah 需要字节码来生成 JNI header ?

java - 使用多个表单在 View 上提交表单时出现 Spring "Neither BindingResult nor plain target object for bean name"错误

java - 将 Spring Security AbstractAuthenticationProcessingFilter 迁移到 WebFlux

java - Spring资源返回空白html页面

java - Thymeleaf:将输入文本作为表单操作中的参数传递

java - 如何重试Spring WebClient根据响应重试操作?

java - 服务器发送请求 firebase java.net.protocolException 在读取响应后无法写入请求正文

java - hibernate 和 Spring : EntityManager is Null

java - EJB 事务 - 静态上下文 - 坏主意?