wanderingstu
wanderingstu

Reputation: 325

How to get the name and value of a parameter using RequestParam?

I want to get the name and value of a URL parameter using RequestMapping.

For instance, if I pass in the URL http://localhost:8080/assignment2/trafficcameras?ip_comm_status=bad

I want to isolate the name of the parameter as "ip_comm_status".

And the value of the parameter as "bad".

How would I access the name and value of any parameter pair?

The problem is that I know how to get the value but not the name of a parameter.

ip_comm_status and camera_status are my valid parameter names.

So far I have:

    @ResponseBody
    @RequestMapping(value = "/trafficcameras", params = {"ip_comm_status", "camera_status"}, method = RequestMethod.GET)
    public String parseParams(@RequestParam(value = "ip_comm_status", required = false) String ip_comm_status_val,
            @RequestParam(value = "camera_status", required = false) String camera_status_val) {


    }

Upvotes: 2

Views: 1448

Answers (3)

Ryuzaki L
Ryuzaki L

Reputation: 40088

You can just use Map<String, String> to get all request param names and values

If the method parameter is Map<String, String> or MultiValueMap<String, String> and a parameter name is not specified, then the map parameter is populated with all request parameter names and values.

Here is an example from baeldung

We can also have multiple parameters without defining their names or count by just using Map

@PostMapping("/api/foos")
@ResponseBody
public String updateFoos(@RequestParam Map<String,String> allParams) {
    return "Parameters are " + allParams.entrySet();
}

Which will then reflect back any parameters sent

curl -X POST -F 'name=abc' -F 'id=123' http://localhost:8080/api/foos
-----
Parameters are {[name=abc], [id=123]}

Upvotes: 1

GIIRRII
GIIRRII

Reputation: 88

Try this, I think you are miss placing value in @RequestParam attribute.

@ResponseBody
    @RequestMapping(value = "/trafficcameras", params = {"ip_comm_status", "camera_status"}, method = RequestMethod.GET)
    public String parseParams(@RequestParam(name = "ip_comm_status", required = false) String ip_comm_status_val,
            @RequestParam(name = "camera_status", required = false) String camera_status_val) {


    }

and you are not confusing it with defaultValue,(this value will be used in case no value is passed) of RequestParam i.e (@RequestParam(defaultValue='xx'))

Upvotes: 0

Jllogic
Jllogic

Reputation: 1

Look up @PathVariable.

   @RequestMapping(value = "/ex/foos/{id}", method = GET)
   @ResponseBody
   public String getFoosBySimplePathWithPathVariable(
   @PathVariable("id") long id) {
    return "Get a specific Foo with id=" + id;
}

Upvotes: 0

Related Questions