简体   繁体   中英

Spring @RequestParam - Mixing named params and Map<String,String> params

I'm writing a Spring Boot application which receives parameters via REST endpoint and forwards them to another system. The received params contain some known fields but may also contain multiple variable fields starting with filter followed by an undefined name:

example.com?id=1&name=foo&filter1=2&filterA=B&[...]&filterWhatever=something

As you can see there are params id and name , and multiple params starting with filter . When calling the target system, I need to remove filter from the param keys and use everything after that as key:

targetsystem.com?id=1&name=foo&1=2&A=B&[...]&whatever=something (no more filter in keys)

This itself is not a problem, I can just just @RequestParam Map<String, String> params , stream/loop the params and modify as I want. But using Swagger as API documentation tool, I want to list all known parameters, so clients can see what is actually supported.

I tried mixing named params and catch-all params, but it doesn't recognize a handler:

myEndpoint(final @RequestParam String id, final @RequestParam String name, final @RequestParam Map<String, String> remainingParams)

Is it possible to map specific params and catch everything else in Map<String,String> ? Or are there other possiblities, like mapping all params starting with filter using regex pattern?

Unfortunately I can't change source and target systems.

If your only concern with using a generic map is simply Swagger being accurate, why not just add the @ApiImplicitParams annotation to your endpoint? This would let you specify which params are required in your Swagger output:

@ApiImplicitParams(value = {
   @ApiImplicitParam(name = "name", type = "String", required = true, paramType = "query"),
   @ApiImplicitParam(name = "id", type = "String", required = true, paramType = "query")
})

You could make a class, eg

@Data
public class Paramss {

    @NotNull
    private String a;
    private String b;
}

and then

@GetMapping
public Object params( @Valid @ModelAttribute Paramss params ) {
    return params;
}

See also: Spring @RequestParam with class

Try

@RequestMapping
public String books(@RequestParam Map<String, String> requestParams, Other params)
{ 
     //Your code here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM