類添加注解@RequestMapping報(bào)錯(cuò)HTTP Status 404
為類添加了@RequestMapping注解后,運(yùn)行報(bào)錯(cuò)404,路徑不對(duì),找了半天才發(fā)現(xiàn)原來(lái)是我的視圖解析器的前綴沒有寫正確
在WEB-INF前面少加了一個(gè)/,加上之后運(yùn)行ok
springMVC使用@RequestMapping遇到的問題
1.簡(jiǎn)介
@RequestMapping既可以定義Controller,也可以定義方法Controller中的方法,主要是用來(lái)映射url的請(qǐng)求路徑
2.屬性簡(jiǎn)介
-
value
:指定請(qǐng)求的實(shí)際地址,指定的地址可以是URI Template 模式(后面將會(huì)說(shuō)明); -
method
:指定請(qǐng)求的method類型, GET、POST、PUT、DELETE等; -
consumes
:指定處理請(qǐng)求的提交內(nèi)容類型(Content-Type),例如application/json, text/html; -
produces
:指定返回的內(nèi)容類型,僅當(dāng)request請(qǐng)求頭中的(Accept)類型中包含該指定類型才返回 -
params
:指定request中必須包含某些參數(shù)值是,才讓該方法處理。 -
headers
:指定request中必須包含某些指定的header值,才能讓該方法處理請(qǐng)求。
3.測(cè)試使用時(shí)遇到的問題
先看源代碼:
1
2
3
4
5
6
7
8
9
10
|
@RequestMapping (value= "/api/{wayName}" ) public void getData( @PathVariable String wayName, @RequestParam ( "appkey" ) int appkey, @RequestParam ( "type" ) int type){ System.out.println( "wayName:" +wayName+ "--appkey:" +appkey+ "--type:" +type); } @RequestMapping (value= "/test" ) public void test(){ System.out.println( "test----------commmin" ); } |
訪問/api/test時(shí)報(bào)HTTP Status 404 -錯(cuò)誤,訪問/test時(shí)也會(huì)報(bào) HTTP Status 404 -錯(cuò)誤
有時(shí)會(huì)報(bào)Circular view path [list]: would dispatch back to the current handler URL [/list] again錯(cuò)誤
在網(wǎng)上查了資料,了解到每個(gè)controller在初始化,如果你沒有聲明viewResolver,spring會(huì)注冊(cè)一個(gè)默認(rèn)的viewResolver給controlller,這個(gè)viewResolver本人簡(jiǎn)單的理解就是一個(gè)呈現(xiàn)處理結(jié)果到前端的工具,如果你視圖的路徑和請(qǐng)求路徑一樣,就會(huì)出現(xiàn)死循環(huán)。
或者你如果在你的方法中沒有返回?cái)?shù)據(jù)到前端,這兩個(gè)錯(cuò)誤都有可能會(huì)出現(xiàn)。
所以最終的解決方法就是返回?cái)?shù)據(jù)到前端
解決后的源碼是
1
2
3
4
5
6
7
8
9
10
11
|
@RequestMapping (value= "/api/{wayName}" ) @ResponseBody public String getData( @PathVariable String wayName, @RequestParam ( "appkey" ) String appkey, @RequestParam ( "type" ) String type){ return "wayName:" +wayName+ "--appkey:" +appkey+ "--type:" +type; } @RequestMapping (value= "/test" ) public void test(HttpServletRequest request,HttpServletResponse response) throws IOException{ response.getWriter().print( "Hello World" ); } |
其中@ResponseBody是表示返回的數(shù)據(jù)輸出到輸出流中。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/IRainReally/article/details/80594805