How to use multiple @RequestMapping annotations in spring?

JavaSpringSpring Mvc

Java Problem Overview


Is it possible to use multiple @RequestMapping annotations over a method?

Like :

@RequestMapping("/")
@RequestMapping("")
@RequestMapping("/welcome")
public String welcomeHandler(){
  return "welcome";
}

Java Solutions


Solution 1 - Java

@RequestMapping has a String[] value parameter, so you should be able to specify multiple values like this:

@RequestMapping(value={"", "/", "welcome"})

Solution 2 - Java

From my test (spring 3.0.5), @RequestMapping(value={"", "/"}) - only "/" works, "" does not. However I found out this works: @RequestMapping(value={"/", " * "}), the " * " matches anything, so it will be the default handler in case no others.

Solution 3 - Java

Doesn't need to. RequestMapping annotation supports wildcards and ant-style paths. Also looks like you just want a default view, so you can put

<mvc:view-controller path="/" view-name="welcome"/>

in your config file. That will forward all requests to the Root to the welcome view.

Solution 4 - Java

The shortest way is: @RequestMapping({"", "/", "welcome"})

Although you can also do:

  • @RequestMapping(value={"", "/", "welcome"})
  • @RequestMapping(path={"", "/", "welcome"})

Solution 5 - Java

The following is acceptable as well:

@GetMapping(path = { "/{pathVariable1}/{pathVariable1}/somePath", 
                     "/fixedPath/{some-name}/{some-id}/fixed" }, 
            produces = "application/json")

Same can be applied to @RequestMapping as well

Solution 6 - Java

It's better to use PathVariable annotation if you still want to get the uri which was called.

@PostMapping("/pub/{action:a|b|c}")
public JSONObject handlexxx(@PathVariable String action, @RequestBody String reqStr){
...
}

or parse it from request object.

Solution 7 - Java

Right now with using Spring-Boot 2.0.4 - { } won't work.

@RequestMapping

still has String[] as a value parameter, so declaration looks like this:

 @RequestMapping(value=["/","/index","/login","/home"], method = RequestMethod.GET)

** Update - Works With Spring-Boot 2.2**

 @RequestMapping(value={"/","/index","/login","/home"}, method = RequestMethod.GET)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwunteeView Question on Stackoverflow
Solution 1 - JavaEd BranninView Answer on Stackoverflow
Solution 2 - JavaAlan ZhongView Answer on Stackoverflow
Solution 3 - JavaRobby PondView Answer on Stackoverflow
Solution 4 - JavaMarcoView Answer on Stackoverflow
Solution 5 - JavaPritam BanerjeeView Answer on Stackoverflow
Solution 6 - JavaCQLIView Answer on Stackoverflow
Solution 7 - JavaFalconView Answer on Stackoverflow