Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple @RequestMapping annotations in spring?

People also ask

Can we have multiple @RequestMapping?

You can have multiple request mappings for a method. For that add one @RequestMapping annotation with a list of values.

Can two controllers have same request mapping?

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

What is the use of @RequestMapping annotation?

annotation. 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.

Which of these are valid usage of @RequestMapping annotation in Spring MVC?

The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods.


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

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


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.


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.


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

Although you can also do:

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

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.