【问题标题】:Missing parameter exception缺少参数异常
【发布时间】:2020-01-05 02:50:36
【问题描述】:

尽管没有丢失值,但在 Spring Boot 上发出请求并获取缺少参数异常。解决数独的项目

请求地址为:http://localhost:8080/solveSudoku/getCellAnswer/0/0

@GetMapping(value = "/getCellAnswer/{row}/{column}")
public Integer getCellAnswer(@RequestParam Integer row, @RequestParam Integer column) {
    return service.solveCell(row, column);
}

以下是错误信息:

{

“时间戳”:1567388255973,

“状态”:400,

“错误”:“错误请求”,

“异常”:“org.springframework.web.bind.MissingServletRequestParameterException”,

"message": "必需的整数参数 'row' 不存在",

“路径”:“/solveSudoku/getCellAnswer/0/0”

}

【问题讨论】:

  • 您使用的是路径变量。请求参数位于 URI 之后,例如myuri.com/pathVariable /pathVariable?requestParam=0 将您的注释切换到 PathVariable
  • 你需要@PathVariable 而不是@RequestParam

标签: java spring-boot http-request-parameters


【解决方案1】:

使用 @PathVariable 您的网址将类似于: http://localhost:8080/solveSudoku/getCellAnswerWithPath/1/2

你的代码是这样的

@GetMapping(value = "/getCellAnswerWithPath/{row}/{col}")
    public ResponseEntity<Integer> getCellAnswerWithPath(@PathVariable int row, @PathVariable int col) {

        return new ResponseEntity<>(service.solveCell(row,col), HttpStatus.OK);

    }

在这里,您必须使用正确的 HttpStatus 代码添加 ResponseEntity

使用 @RequestParam 您的网址将类似于: http://localhost:8080/solveSudoku/getCellAnswer?row=1&col=2

你的代码是这样的

@GetMapping(value = "/getCellAnswer")
    public ResponseEntity<Integer> getCellAnswer(@RequestParam(value="row") int row, @RequestParam(value="col") int col) {

        return new ResponseEntity<>(service.solveCell(row,col), HttpStatus.OK);

在这里,您必须使用正确的 HttpStatus 代码添加 ResponseEntity

这里是进口

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

【讨论】:

    【解决方案2】:

    您需要使用PathVariable并指定PathVariable 名称

    @GetMapping(value = "/getCellAnswer/{row}/{column}")
    public Integer getCellAnswer(@PathVariable (name="row") Integer row, 
         @PathVariable (name="column") Integer column) {
                return service.solveCell(row, column);
        }
    

    【讨论】:

      【解决方案3】:

      您当前为此使用了错误的注释。使用@RequestParam,请求将如下所示,只需使用@GetMapping(value = "/getCellAnswer")

      http://localhost:8080/solveSudoku/getCellAnswer?row=0&column=0
      

      您可能正在尝试使用@PathVariable,使用{row}{column} 定义模板。为此,您可以更改代码,如下所示:

      @GetMapping(value = "/getCellAnswer/{row}/{column}")
      public Integer getCellAnswer(@PathVariable Integer row, @PathVariable Integer column) {
          return service.solveCell(row, column);
      }
      

      您可以查看文档 herehere

      【讨论】:

      • 谢谢大家。我以前试过这个,但它仍然给了我错误。还有什么可能吗?
      猜你喜欢
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 2010-10-17
      • 2021-02-12
      相关资源
      最近更新 更多