今天用postman工具測試接口時,返回404錯誤,花費很久時間處理,之前用了這么久的工具不至於出錯,只可能程序出錯了。
報錯信息:
@ResponseBody
來看看為什么要添加這個注解
The course documentation states that this annotation serves the function to: ensure that the result will be written to the HTTP response by an HTTP Message Converter (instead of an MVC View).
The annotation means is that the returned value of the method will constitute the body of the HTTP response.
The returned value of the method will constitute the body of the HTTP response.
說的就是一個意思,就是 @ResponseBody 用於對方法進行注釋, 表示該方法的返回的結果將直接寫入 HTTP 響應正文(Http Response Body)中。我之前控制層代碼里有返回值,類型為 CommonReturnType 的通用返回值類型,我把返回值去掉后,方法改為 void,無任何返回值, 雖然在前端的調試中,各種數據依然正常,但是前端頁面獲取不到控制層方法的返回值,在 response body 中無內容,導致點擊前端頁面的按鈕不會有任何現象發生,雖然此時后端邏輯正確無誤,請求也成功了,后端程序正常運行,數據庫入庫操作都實現了,但是前端獲取不到呀。所以我這里必須給該方法一個返回值,且要通過注解形式將返回值加到 Http response body 中。 如果沒有這個注解,就會拋出上面的 responseText 異常信息。
附正確的用法:
import com.gdiot.model.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Slf4j
@Controller
@RequestMapping("/data")
@ResponseBody
public class TestController {
@RequestMapping("/test")
public String test_get(){
log.info(String.format("test_get"));
return "test_get";
}
}