Home > Software engineering >  Is there a way to support two or more parameter names that represent the same value with spring requ
Is there a way to support two or more parameter names that represent the same value with spring requ

Time:08-26

So as an example, lets say we have the following method.

@PostMapping("/api/foos")
@ResponseBody
public String addFoo(@RequestParam(name = "fId") String fooId) { 
    return "ID: "   fooId;
}

Now imagine that users sometimes submit fId and sometimes use f_id. I want to be able to accept both/either with one as the preferred if they are both submitted.

something like:

@PostMapping("/api/foos")
@ResponseBody
public String addFoo(@RequestParam(name = "fId" or "f_id") String fooId) { 
    return "ID: "   fooId;
}

I don't believe the code above is valid but it illustrates what I'm trying to do if it can be done. I know the manual solution is to accept both params as separate params and then create logic to determine which to use for the response. I'm just wondering if there is a better less code intense solution!

CodePudding user response:

I don't think you can do that but you could just check in the java code like:

public String addFoo(
  @RequestParam(name = "fId", required=false) String fooId, 
  @RequestParam(name = "f_Id", required=false) String foo_Id
) { 
  if (fooId == null) fooId = foo_Id;
  return "ID: "   fooId;
}

A bit simplistic but that shows the idea.

CodePudding user response:

You shouldn't handle this in the backend. Your endpoint should receive always the same parameters (if you only need 1, then just 1 RequestParam). Also, I don't know the context, but for each form, you should only have 1 input for 1 objective. If the same parameter can come from several inputs, maybe you should reconsider your form.

However, if this is the case and can't be avoided, I would suggest you add a hidden input inside your form, and when the user presses the submit button, first fill the hidden input with the value you need and then send, make the backend call.

  • Related