I'm working on a Spring MVC project using Annotated Controller.
One thing that I'm interested in is about the order which @RequestMapping
instruction to be processed.
For example, I want all /green/basic/welcome
to be mapped to GreenController.welcome()
but green/{treeId}/{treeName}
to be mapped to GreenController.viewTree(treeId, treeName)
.
I guess I need to specify two @RequestMapping
with @RequestMapping
of /green/basic/welcome
to be processed first, so that it won't be interpreter as a call to GreenControllerviewTree("basic", "welcome")
.
Can you guys guide me on that?
One of the most important annotations in spring is the @RequestMapping Annotation which is used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP requests to handler methods of controllers.
RequestMapping annotation is used to map web requests onto specific handler classes and/or handler methods. @RequestMapping can be applied to the controller class as well as methods. Today we will look into various usage of this annotation with example and other annotations @PathVariable and @RequestParam .
A @RequestMapping on the class level is not required. Without it, all paths are simply absolute, and not relative. This means if you specify the class level annotations, the URL shall be relative, it shall be http://localhost:8080/users/user (URL to Handler mapping) and likewise.
You cannot. A URL can only be mapped to a single controller. It has to be unique.
An exact match for a RequestMapping
will take precedence over one with a PathVariable
. So you would have two request mappings like you pointed out. One to handle the specific url, and the variable version will catch everything else. Spring checks for direct path matches before checking for path variable matches, so order does not matter unless you have two request mappings with the same number of path variables, which may spit out an IllegalStateException
Check the source of org.springframework.web.servlet.handler.AbstractHandlerMethodMapping
for the specifics. It is handled in lookupHandlerMethod()
.
To determine the best match of two RequestMapping
s that aren't exact matches, the compareTo() method of RequestMappingInfo
is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With