如果我有一個方法有大約10個請求引數,而我可能并不總是需要所有的引數
public ResponseEntity<String> sendSomethingBack( String optionalRequestParam1。
String optionalRequestParam2。
...
String optionalRequestParam10)
所以在這個頭中,我希望有這樣的東西
在這個頭中,我希望有這樣的東西。
@GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(@RequestParam RequestParamBuilder requestParamBuilder)
然后它就會為我建立一個物件,并填寫所有通過發送的有效引數,其余的為空或其他東西
。uj5u.com熱心網友回復:
你可以有多個引數而不需要定義它們的名字,只需使用一個Map:
@GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(@RequestParam Map<String, Object> params) {
log.info("Params: {}", params.entrySet()。
如何進行呼叫:
curl --location --request GET 'http://localhost:8080/whatever?integer=45&string="some text"& boolean=true'
輸出:
Params: [integer=45, string="some text", boolean=true]/p>
uj5u.com熱心網友回復:
如果你想讓引數被傳遞到一個物件中,你可以像以前一樣使用一個POJO,但要去掉@RequestParam的符號:
@GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(RequestParamBuilder requestParamBuilder)
然后為RequestParamBuilder創建一個類。你可以將POJO中的欄位標記為@NotNull等來處理驗證,并且只用請求中包含的引數來構建物件,但是如果你希望spring以這種方式進行驗證,POJO必須被注釋為@Valid:
@GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(@Valid RequestParamBuilder requestParamBuilder)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/313442.html
標籤:
