springboot webflux 参数传递(json传递)
json传递的参数数据可用注解读取,也可用路由函数处理
*************************
注解:@RequestBody
******************
controller 层
HelloController
@RestController
public class HelloController {
@RequestMapping("/hello2")
public String hello2(@RequestBody Person person){
System.out.println(person);
return person.toString();
}
@RequestMapping("/hello3")
public Mono<Person> hello3(@RequestBody Mono<Person> person){
return person.doOnNext(System.out::println);
}
@RequestMapping("/hello4")
public Flux<Person> hello4(@RequestBody Flux<Person> person){
return person.doOnNext(System.out::println);
}
}
******************
前端页面
hello.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/js/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function () {
const data = {
name: $("#name").val(),
age: $("#age").val()
};
$.post({
url: "./hello4",
contentType: "application/json",
data: JSON.stringify(data),
success: function () {
}
})
})
})
</script>
</head>
<body>
<form th:align="center">
name: <input type="text" id="name" name="name"><br>
age: <input type="text" id="age" name="age"><br>
<button id="btn">提交</button>
</form>
</body>
</html>
*************************
路由函数
CustomRouterConfig
@Configuration
public class CustomRouterConfig {
@Bean
public RouterFunction<ServerResponse> initRouterFunction(){
return RouterFunctions.route()
.POST("/hello3",serverRequest -> {
Mono<Person> person=serverRequest.bodyToMono(Person.class);
return ServerResponse.ok().body(person.doOnNext(System.out::println),Person.class);
})
.POST("/hello4",serverRequest -> {
Flux<Person> person=serverRequest.bodyToFlux(Person.class);
return ServerResponse.ok().body(person.doOnNext(System.out::println),Person.class);
})
.build();
}
}