WebFlux的validation比以前的版本簡單了很多。
先看pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<exclusions>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-transport-native-epoll</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
要校驗的bean:
public class RecordFileSaveReq {
@NotNull(message = "sessionid不能爲空")
@Size(max=50, message = "sessionid不能超過50字節")
@Getter @Setter
private String sessionid;
}
Controller很簡單,如果校驗失敗,就返回失敗信息;否則返回成功:
@Controller
public class FileSaveController {
@PostMapping(name = "/recordFile/save")
@ResponseBody
public Mono<CommonOutput> save(@Valid @RequestBody Mono<RecordFileSaveReq> req) {
return Mono.create(sink -> {
req.doOnError(WebExchangeBindException.class, throwable -> {
sink.success(fail(throwable.getFieldErrors().toString()));
}).doOnNext(r -> {
sink.success(success());
}).subscribe();
});
}
}
看一下測試代碼:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = StorageServApp.class)
@ActiveProfiles("constants")
public class FileSaveTest {
@Autowired
private WebTestClient client;
@Test
public void validError() {
RecordFileSaveReq req = new RecordFileSaveReq();
//req.setCalledNbr("");
Flux<CommonOutput> rn = client.post().uri("/recordFile/save")
.body(Mono.just(req), RecordFileSaveReq.class)
.exchange()
.returnResult(CommonOutput.class).getResponseBody();
StepVerifier.create(rn)
.assertNext(co -> {
assertEquals(1, co.getCode().intValue());
System.out.println(co.getInfo());
})
.verifyComplete();
}
}
運行結果:
[Field error in object 'recordFileSaveReqMono' on field 'sessionid': rejected value [null]; codes [NotNull.recordFileSaveReqMono.sessionid,NotNull.sessionid,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [recordFileSaveReqMono.sessionid,sessionid]; arguments []; default message [sessionid]]; default message [sessionid不能爲空]]