淺談@RequestMapping注解的注意點
@RequestMapping注解注意點
類上加沒加@RequestMappin注解區(qū)別
1.如果類上加了 @RequestMappin注解,那么就會去該注解對應(yīng)的路徑下去找頁面,如果沒有對應(yīng)的頁面就會報錯。
舉例說明:
@RequestMapping("/user")
public class UserController {
?? ?@RequestMapping("/requestParam51")
? ? public String requestParam51(String[] name) {
? ? ? ?return "index.jsp";
? ? }
}對應(yīng)的跳轉(zhuǎn)頁面會去user目錄下去找,找不到就會報錯。
2.如果類上沒有加@RequestMapping注解,就會直接去根路徑下去找頁面
3.如果為跳轉(zhuǎn)的頁面加了"/",還是會去根路徑下去找對應(yīng)的頁面。
舉例:
@RequestMapping("/user")
public class UserController {
?? ?@RequestMapping("/requestParam51")
? ? public String requestParam51(String[] name) {
? ? ? ?return "/index.jsp";
? ? }
}@RequestMapping一個坑
今天發(fā)現(xiàn)了RequestMapping注解的一個坑:
當(dāng)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 或者h(yuǎn)ttp://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
單看異常信息,還以為是有重名的路徑,結(jié)果搜遍了工程也沒找到重名的類,后來"v1.0"改成"v1",就正常運行了。
順帶測試了下,發(fā)現(xiàn)改成1.0也是同樣的錯誤。
之后再把一個方法上RequestMapping的value去掉,采用默認(rèn)寫法:
? ? @RequestMapping("/b")
? ? public @ResponseBody
? ? Object getB() {
? ? ? ? return ?"{\"test\" : \"b\"}";
? ? }再運行起來,訪問http://localhost:port/v1.0/a或者h(yuǎn)ttp://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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
如何在IDE部署springboot項目(有swagger和無swagger都是一樣的)到服務(wù)器或者虛擬機(jī)上的docke
這篇文章主要介紹了如何在IDE部署springboot項目(有swagger和無swagger都是一樣的)到服務(wù)器或者虛擬機(jī)上的docker,本文給大家分享我的安裝歷程,需要的朋友可以參考下2023-01-01
SpringBoot Event實現(xiàn)異步消費機(jī)制的示例代碼
這篇文章主要介紹了SpringBoot Event實現(xiàn)異步消費機(jī)制,ApplicationEvent以及Listener是Spring為我們提供的一個事件監(jiān)聽、訂閱的實現(xiàn),內(nèi)部實現(xiàn)原理是觀察者設(shè)計模式,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2024-04-04
Java利用OSHI實現(xiàn)獲取機(jī)器的硬件信息
OSHI(Operating System and Hardware Information)是一個開源的Java庫,用于獲取操作系統(tǒng)和硬件的詳細(xì)信息,下面我們就來看看他的具體使用吧2024-11-11

