1. 程式人生 > >handleTypeMismatch Failed to bind request element錯誤記錄

handleTypeMismatch Failed to bind request element錯誤記錄

當時遇到這個錯誤的時候,也是很懵逼,感覺自己並沒有寫錯,怎麼會報這個錯誤,後來冷靜分析了一下,才發現是介面定義的問題,= =。先上一下錯誤日誌:

handleTypeMismatch Failed to bind request element: 
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: 
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer

看一下我的兩個請求介面,都是GET請求:

/**查詢所有課程*/
@GetMapping("/app/society/courses")
public Object userInfo(){
    ...
    ...
}

/**根據課程ID,查詢課程詳情*/
@GetMapping("/app/society/{course_id}")
public Object userInfo(@PathVariable("course_id")Integer courseId){
    ...
    ...
}

看到我的兩個介面定義,你會不會發現了什麼。其實當我請求/app/society/courses介面時,才報的這個錯,但為什麼會報String轉Integer異常呢,是因為Spring將“courses”

作為URL引數,將請求發給了/app/society/{course_id},但course_id定義的是Integer,所以會Spring會報“courses”這個字串從String轉Integer錯誤!!!!!!!!!!

傷心欲絕,總以為自己沒有錯,其實還是自己錯了,= =.

好了,解決方案大家應該都很清楚了,只需要修改下第二個介面的URI就可以了,修改後的例子如下:

/**查詢所有課程*/
@GetMapping("/app/society/courses")
public Object userInfo(){
    ...
    ...
}

/**根據課程ID,查詢課程詳情*/
@GetMapping("/app/society/{course_id}/info")
public Object userInfo(@PathVariable("course_id")Integer courseId){
    ...
    ...
}