首页 > 解决方案 > 是否可以从 GetMapping("/") 处理程序返回 Mono.just("index") ?

问题描述

让我们考虑这个请求处理程序:

@GetMapping("/")
public Mono<String> index(Model model) {
  model.addAttribute("list", Flux.just("item1", "item2"));
  return Mono.just("list"); // <- Template name
}

如果目录中有index.html模板,templates则不执行此处理程序。

如果我Mono.just("index")从处理程序返回:

@GetMapping("/")
public Mono<String> index(Model model) {
  model.addAttribute("list", Flux.just("item1", "item2"));
  return Mono.just("index"); // <- Template name
}

该处理程序仍未使用。

看来我必须从目录中删除index.html模板才能处理路由。templatesGetMapping("/")

所以我的问题是,是否可以Mono.just("index")GetMapping("/")处理程序返回 a ?

标签: javaspring-webfluxproject-reactor

解决方案


根据本书,你应该使用@Controller 而不是@RestController。

这是另一个示例:

@GetMapping("/welcome")
    public Mono<String> hello(final Model model) {
        model.addAttribute("name", "Foo");
        model.addAttribute("city", "Bar");

        String path = "hello";
        return Mono.create(monoSink -> monoSink.success(path));
    }

对应的thymeleaf html页面:

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8"/>
    <title>Greet</title>
</head>

<body>

<p th:text="${name}"></p> lives in <p th:text="${city}"></p> 

</body>
</html> 

推荐阅读