日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Required String paramter ‘username‘ is not present

作者:Pisces_224 更新時間: 2022-02-27 編程語言

原因

Spring Boot的注解@RequestParam不支持接受請求體內(nèi)的json數(shù)據(jù)。

以下為轉(zhuǎn)載他人部分:https://blog.csdn.net/qq_39506912/article/details/90107756
重點(diǎn)為對三個注解的比較


錯誤分析

使用Post向接口發(fā)送json數(shù)據(jù)時顯示如下錯誤:

WARN 13392 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by handler execution: org.springframework.web.bind.MissingServletRequestParameterException: 
Required String parameter 'userName' is not present

 

    查看json數(shù)據(jù)并無格式問題,查閱資料發(fā)現(xiàn)是接口接受傳參問題,我這里使用了@RequestParam注解來接受數(shù)據(jù),而這個注解不支持接受請求體內(nèi)的json數(shù)據(jù)。

    @PostMapping("/account")
    public Object insertAccount(@RequestParam("userName") String userName) {
    	...
    
     

      解決方法

      下面是對@PathVariable@RequestParam@RequestBody三者的比較

      注解 支持的類型 支持的請求類型 支持的Content-Type 請求示例
      @PathVariable url GET 所有 /test/{id}
      @RequestParam url GET 所有 /test?id=1
      Body POST/PUT/DELETE/PATCH form-data或x-www.form-urlencoded id:1
      @RequestBody Body POST/PUT/DELETE/PATCH json {"id":1}

      將接口改成以@RequestBody注解方式接受json請求數(shù)據(jù),而后將接收到的json數(shù)據(jù)轉(zhuǎn)化為json對象,可以使用json對象的get()方法取得參數(shù)值,代碼如下:

      @PostMapping("/account")
      public Object insertAccount(@RequestBody JSONObject jsonParam) {
      	String userName=jsonParam.get("userName").toString()
      	...
      
       

        原文鏈接:https://blog.csdn.net/qq_36256590/article/details/121822876

        欄目分類
        最近更新