欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

There was an unexpected error (type=Bad Request, status=400).以及@RequestBody和@RequestParam区别

程序员文章站 2022-05-29 22:33:45
...

今天在使用spring boot做设备微服务的开发时,报出了标题中的错误,完成的错误信息如下

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Feb 02 15:42:15 CST 2021
There was an unexpected error (type=Bad Request, status=400).

翻译最后一句为:发生意外错误(类型=错误的请求,状态= 400) ,如下贴出我的代码

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public ResponseDto getDeviceDetail(
            @RequestHeader(name = Constant.HEADER_X_TRACE_ID, required = false) String traceId,
            @Validated @RequestBody DetailDeviceRequestBody requestBody,
            @PathVariable String requestPath,
            @PathVariable String requestCategory
    ) {
        。。。。。。
        String sn = requestBody.getSn();
        if ( isBlank(sn)) {
            return new ResponseDto(ErrorResponse.REQUEST_ERROR.getCode(),ErrorResponse.REQUEST_ERROR.getMessage());
        }
        。。。
        return iDeviceService.getDeviceDetail(deviceEntity);
    }

问题出现在这里 @Validated @RequestBody DetailDeviceRequestBody requestBody,,我明明是get请求,却使用@RequestBody去接收数据,然而get请求是没有请求体的,因为报出了这样的,我们可以使用@RequestParam来接收,如下代码所示

   @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public ResponseDto getDeviceDetail(
            @RequestHeader(name = Constant.HEADER_X_TRACE_ID, required = false) String traceId,      
            @RequestParam(required = false) String sn,
            @PathVariable String requestPath,
            @PathVariable String requestCategory
    ) {
        if ( isBlank(sn)) {
            return new ResponseDto(ErrorResponse.REQUEST_ERROR.getCode(),ErrorResponse.REQUEST_ERROR.getMessage());
        }
        。。。
        return iDeviceService.getDeviceDetail(deviceEntity);
    }

这样就能轻松地接收get的请求值了。

下面链接是说明@RequestBody和@RequestParam区别:@RequestBody和@RequestParam区别