淺談@RequestMapping注解的注意點
@RequestMapping注解注意點
類上加沒加@RequestMappin注解區(qū)別
1.如果類上加了 @RequestMappin注解,那么就會去該注解對應的路徑下去找頁面,如果沒有對應的頁面就會報錯。
舉例說明:
@RequestMapping("/user")
public class UserController {
?? ?@RequestMapping("/requestParam51")
? ? public String requestParam51(String[] name) {
? ? ? ?return "index.jsp";
? ? }
}對應的跳轉(zhuǎn)頁面會去user目錄下去找,找不到就會報錯。
2.如果類上沒有加@RequestMapping注解,就會直接去根路徑下去找頁面
3.如果為跳轉(zhuǎn)的頁面加了"/",還是會去根路徑下去找對應的頁面。
舉例:
@RequestMapping("/user")
public class UserController {
?? ?@RequestMapping("/requestParam51")
? ? public String requestParam51(String[] name) {
? ? ? ?return "/index.jsp";
? ? }
}@RequestMapping一個坑
今天發(fā)現(xiàn)了RequestMapping注解的一個坑:
當RequestMapping用于Class上時,不能用1.0,v1.0這樣帶小數(shù)點的value值做開頭
@Controller
@RequestMapping(value = "/v1.0")
public class TestController {
? ? @RequestMapping(value = "/a", method = RequestMethod.GET, produces = "application/json")
? ? public @ResponseBody
? ? Object getA() {
? ? ? ? return ?"{\"test\" : \"a\"}";
? ? }
? ? @RequestMapping(value = "/b", method = RequestMethod.GET, produces = "application/json")
? ? public @ResponseBody
? ? Object getB() {
? ? ? ? return ?"{\"test\" : \"b\"}";
? ? }
}如上代碼運行后,訪問http://localhost:port/v1.0/a 或者http://localhost:port/v1.0/b 時都會報錯:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'testController' bean method
public java.lang.Object com.my.test.controller.TestController.getB()
to {[/v1.0],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}: There is already 'testController' bean method
單看異常信息,還以為是有重名的路徑,結果搜遍了工程也沒找到重名的類,后來"v1.0"改成"v1",就正常運行了。
順帶測試了下,發(fā)現(xiàn)改成1.0也是同樣的錯誤。
之后再把一個方法上RequestMapping的value去掉,采用默認寫法:
? ? @RequestMapping("/b")
? ? public @ResponseBody
? ? Object getB() {
? ? ? ? return ?"{\"test\" : \"b\"}";
? ? }再運行起來,訪問http://localhost:port/v1.0/a或者http://localhost:port/v1.0/b 就會變成404錯誤。
HTTP Status 404 - /v1.0/a type Status report message /v1.0/a description The requested resource is not available.
沒深究根本原因,估計是Spring的小bug,以后避免帶小數(shù)點的路徑頭。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
BeanUtils.copyProperties()拷貝id屬性失敗的原因及解決
這篇文章主要介紹了BeanUtils.copyProperties()拷貝id屬性失敗的原因及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
為什么 Java 8 中不需要 StringBuilder 拼接字符串
java8中,編輯器對“+”進行了優(yōu)化,默認使用StringBuilder進行拼接,所以不用顯示的使用StringBuilder了,直接用“+”就可以了。下面我們來詳細了解一下2019-05-05
java 中序列化NotSerializableException問題解決辦法
這篇文章主要介紹了java 中序列化NotSerializableException問題解決辦法的相關資料,這里對序列化問題進行描述說明,并提供解決辦法,希望能幫助到大家,需要的朋友可以參考下2017-08-08

