Spring Rest RequestMethod.GET 在缺少 @RequestParam required=true 时返回 400 Bad Request

问题描述 投票:0回答:4

我是 Spring 和 Rest 端点的新手。

我有一个控制器,它接受

@RequestParam
并返回
JSON Response

默认情况下

@RequestParam required = "true"
,这就是我需要的。

我正在使用Spring 3.1.3

这是我在控制器中的获取方法:

@Controller
@RequestMapping("/path")
public class MyController{
        @RequestMapping(value = "/search/again.do", method = RequestMethod.GET, produces = {
        "application/json"
    })
    public ResponseEntity<?> find(@RequestParam(value = "test", required = true) final String test) {
        return new ResponseEntity<String>("Success ", HttpStatus.OK);
    }
}

当我发送带有请求参数的 get 时,它会到达端点,这正是我所期望的。

示例:path/search/again.do?test=yes

一切都很完美。

这就是我遇到问题的地方:

当我发送缺少该值的 Get 时:

示例:路径/search/again.do

我收到 400 错误请求。也许这是正确的。

但我想要实现的是。当 GET 请求中缺少所需值时。

我可以发送 JSON 响应,因为缺少

@RequestParam
test

任何人都可以指导我如何实现这一目标。

我不确定我错过了什么。

提前致谢。

java json spring rest spring-mvc
4个回答
4
投票

如果你仔细观察你的代码,你会发现答案就在你眼前。只需将

required
更改为
false
即可。当用户没有为 GET 参数
test
提供值时,您可以返回一条特殊消息。

@Controller
@RequestMapping("/path")
public class MyController {
    @RequestMapping(value = "/search/again.do", method = RequestMethod.GET, produces = {
    "application/json"
    })
    public ResponseEntity<?> find(@RequestParam(value = "test", required = false) final String test) {
        if (test == null) {
            return new ResponseEntity<String>("test parameter is missing", HttpStatus.OK);
        }
        else {
            return new ResponseEntity<String>("Success ", HttpStatus.OK);
        }
    }
}

2
投票

解决方案1:您可以在控制器中使用自定义@ExceptionHandler,例如

@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<?> paramterValidationHandler(HttpServletResquest request){
 //validate the request here and return an ResponseEntity Object
}

解决方案 2:将是自定义 spring ErrorController,我自己从未尝试过,但可以覆盖它。

解决方案3:您可以编写一个ControllerAdvice来进行全局控制器异常处理。


0
投票

如果设置好参数就需要测试。如果没有该参数,您就无法发送请求。尝试更改参数 required= false 并处理方法中缺少的参数。你可以给我们类似的东西

if(test==null) throw new Exception("Param test missing")


0
投票

我也有类似的问题。我声明了一个 REST 方法参数是必需的,如果我调用端点而不传递该参数,它只会给我一个 400 错误请求。 >如果你不想在客户端有更清晰的错误信息<, too, you can do that by adding following to your

application.yaml
:

server:
  error:
    include-message: always

这会导致类似的结果

{
    "timestamp": "2024-04-09T14:14:31.504+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "Required parameter 'datum' is not present.",
    "path": "/rest/v1/xyz"
}

(fiy:据说这样做会泄露敏感信息,所以想想是否可以:))

© www.soinside.com 2019 - 2024. All rights reserved.