Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordered RequestMapping in spring MVC

Tags:

spring-mvc

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?

like image 939
Phương Nguyễn Avatar asked Feb 24 '10 14:02

Phương Nguyễn


People also ask

What is the use of @RequestMapping in Spring MVC?

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.

What is @RequestMapping annotation in Spring MVC?

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 .

Is @RequestMapping mandatory at class level?

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.

Can two controllers have same request mapping?

You cannot. A URL can only be mapped to a single controller. It has to be unique.


1 Answers

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 RequestMappings that aren't exact matches, the compareTo() method of RequestMappingInfo is used.

like image 78
yincrash Avatar answered Oct 21 '22 16:10

yincrash