user1007895
user1007895

Reputation: 3975

Get value from @RequestParam without specified name

I know that if a parameter looks like this:

@RequestParam("userId") String userId

I can get the value by calling this:

requestParam.value()

But if I don't specify a name, Spring automatically uses the variable name. Like this:

@RequestParam String userId

If the param name isn't specified, how can I access it? I know its possible because Spring does it somehow, but requestParam.value() is blank in this case.

Upvotes: 13

Views: 10002

Answers (4)

Lovro Pandžić
Lovro Pandžić

Reputation: 6400

In case of Java 8, Spring uses StandardReflectionParameterNameDiscoverer, which relies on Java 8 Parameters API.

For details how to set up parameters option and use it via reflection see this answer.

Upvotes: 3

BlackJoker
BlackJoker

Reputation: 3191

Recommend you not to do it that way.Spring use asm to analysis the java bytecode file,and extract parameter name of a method.But some time this does not work,because some .class file does not comprise parameter name,just parameter types,it depends on compiler options.

Upvotes: 4

Tom McIntyre
Tom McIntyre

Reputation: 3699

Spring doesn't populate the request based on the @RequestParam. Rather it populates the method argument annotated with @RequestParam (in a method annotated with @RequestMapping). The parameter given to the @RequestParam annotation tells Spring the name of the request parameter you want it to use as that argument. If you don't provide one, Spring defaults to using the name of the argument (so the 2 examples you give in your question are equivalent).

If you are trying to access a request parameter, you need to know the name of it, regardless of the framework you are using.

Upvotes: 9

atrain
atrain

Reputation: 9265

Just call userId, as in doSomething(userId). Spring binds everything up for you.

Upvotes: 0

Related Questions