鍍金池/ 問答/Java  HTML/ springBoot + axios 做 put 請(qǐng)求。后臺(tái)無法接受數(shù)據(jù)

springBoot + axios 做 put 請(qǐng)求。后臺(tái)無法接受數(shù)據(jù)

1、問題描述:
后臺(tái)使用 springBoot , 前端使用 vue 的 axios 做 put 請(qǐng)求,但是后臺(tái)無法接受到數(shù)據(jù)。

    @PutMapping("/status/{id}")
    public Object updateProductionStatus(@PathVariable("id") String productionId, @RequestBody Integer status)

前端的 請(qǐng)求頭:

clipboard.png

以 json 格式上傳, spring 用 @RequestBody接受數(shù)據(jù)。 但是提示接收不到數(shù)據(jù)。

嘗試使用 @ModelAttribute 接收。 但是 @ModelAttribute 需要使用一個(gè)對(duì)象去接受。 單純的使用 基本數(shù)據(jù)類型, 他會(huì)拋

嚴(yán)重: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.lang.Integer]: No default constructor found; nested exception is java.lang.NoSuchMethodException: java.lang.Integer.<init>()] with root cause
java.lang.NoSuchMethodException: java.lang.Integer.<init>()

這個(gè)異常。

我將參數(shù)使用?status=xxx 的形式 上傳是可以的, 但是問題是,我想把這個(gè)數(shù)據(jù)不寫到URL 上面,想以 request payload 的形式 或者 以 Form data 的形式 上傳, 我該怎么做

回答
編輯回答
陌離殤

一、使用Map接收,因?yàn)槟愕膉son對(duì)象是{status:1},這是一個(gè)鍵值對(duì)

    @PutMapping("/status/{id}")
    public Object updateProductionStatus(@PathVariable("id") String productionId, @RequestBody Map<String,Integer> status)

二、也可以讓axios只發(fā)送1這樣你就可以使用你原來的接口接收

@PutMapping("/status/{id}")
    public Object updateProductionStatus(@PathVariable("id") String productionId, @RequestBody Integer status)

二的具體例子如下

@RestController
public class MyTest {
    
    @PutMapping("/status/{id}")
    public Map getStatusValue(@PathVariable("id") String id, @RequestBody Integer status) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("statusId", status);

        return map;
    }
}

clipboard.png

2017年5月15日 14:51
編輯回答
裸橙

你試一下這個(gè)注解 @RequestParam

2017年12月20日 08:21