【问题标题】:How to convert ModelAndView Spring MVC to spring Webflux如何将 ModelAndView Spring MVC 转换为 Spring Webflux
【发布时间】:2022-01-22 18:45:24
【问题描述】:

如何将以下 Spring MVC 代码转换为 spring webflux?

@GetMapping(path = "/connect")
@ResponseStatus(HttpStatus.FOUND)
public ModelAndView connect() {
  
    String oauthUrl = "https://google.com";
    RedirectView redirect = new RedirectView(oauthUrl);
    redirect.setExpandUriTemplateVariables(false);
    return new ModelAndView(redirect);
  }
    

【问题讨论】:

  • Webflux 不适用于返回模型和视图的 MVC。仅适用于单独返回模型数据。

标签: java spring spring-boot spring-webflux


【解决方案1】:

您可以为此使用Rendering

@Controller
@RequestMapping("/redirect")
public class RedirectController {

    @GetMapping
    public Mono<Rendering> redirect() {
        return Mono.just(Rendering.redirectTo("https://www.google.com").build());
    }
}

【讨论】:

  • 它不起作用,我得到响应正文 {} 和标题 Content-Type: application/json
  • 您在控制器类上使用@Controller 注释吗?查看我更新的示例代码,这可以在我的本地演示中找到。
  • 仍然不行,同样的响应,我可以调试并看到断点处的停止。我正在使用@RestController
  • 需要渲染的时候应该使用@Controller。顾名思义,@RestController 用于 REST 端点,因此需要 application/json 内容类型。
【解决方案2】:
@RestController

public class TestController {


        @GetMapping(path = "/redirect")
    public Mono<ResponseEntity> redirect() {
        return Mono.just(ResponseEntity
                .status(HttpStatus.TEMPORARY_REDIRECT)
                .header("Location", "https://google.com?param=ABCD")
                .build());
    }
}

或者.header(...)可以替换为.location(new URI(...))

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 2018-04-04
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多