Harrison Lee
Harrison Lee

Reputation: 65

The difference between the attribute name, value and path of the annotation @RequestMapping in SpringMVC

I am struggling to understand the differences between the attribute name, path and value in @RequestMapping. I looked into the API, but it doesn't illustrate it clearly. I googled for hours but it just works partially. Can you tell me the details? Thank you!

Upvotes: 0

Views: 1365

Answers (1)

JB Nizet
JB Nizet

Reputation: 691655

Let's see the javadoc. Start with path:

The path mapping URIs (e.g. "/profile").

So that's the path(s) that will be used by Spring to decide if this methd should be called or not, based on the actual path of the request.

Now value:

The primary mapping expressed by this annotation.

This is an alias for path(). For example, @RequestMapping("/foo") is equivalent to @RequestMapping(path="/foo").

So, it's quite clear: value and path are exactly equivalent.

And finally name:

Assign a name to this mapping.

So this is completely different. It gives a name to this mapping. Why could a name be useful for a mapping? You can discover that by clicking on the "See also" classes linked to attrbibute in the documentation. The javadoc for HandlerMethodMappingNamingStrategy says:

Applications can build a URL to a controller method by name with the help of the static method MvcUriComponentsBuilder#fromMappingName [...]

So, as you see, the name of a mapping can be used to construct a URL that will match to a given controller method by using the name of its mapping. That makes it possible to change the path of a mapping without changing it everywhere, by using names rather than paths.

The reference documentation, in addition to the javadoc, should be your first destination. This is usually way more effective when you want to learn about the framework than googling.

Upvotes: 2

Related Questions