Multiple Spring @RequestMapping annotations

北战南征 提交于 2019-11-26 12:34:50

问题


Is it possible to use multiple @RequestMapping spring annotations in a method? Like:

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

回答1:


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

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




回答2:


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.




回答3:


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.




回答4:


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

@RequestMapping

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

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



回答5:


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

Although you can also do:

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



回答6:


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.



来源:https://stackoverflow.com/questions/2513031/multiple-spring-requestmapping-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!