无法在 Spring MVC 控制器中对 POST 请求发送 json 响应

Can't send json response on POST request in Spring MVC controller

我可以毫不费力地发送对象列表以响应 POST 请求并在 VueJs 客户端中接收它

@RequestMapping(value={"/data/parts"}, method = RequestMethod.POST)
@ResponseBody public List<Part> getPartsList( @RequestBody LookupForm lookupForm ) {
        return getService().findParts(lookupForm.getCode(), lookupForm.getName(), lookupForm.getWarehouseCode());
}

但是当我尝试使用自定义 class 响应进行响应时(我什至在 RequestMapping 注释中添加了 produces="application/json"

@RequestMapping(value={"/addPartsRequest"}, method = {RequestMethod.POST}, produces="application/json")
    @ResponseBody public Response addPartsRequest(@RequestBody PartsRequest partsRequest) {
        Response response = new Response("Fail","Your Request failed");
        PartsRequest newRequest = getService().addPartsRequest(partsRequest);
        if (newRequest != null){
            response = new Response("Ok", "The Ticket has been submitted.");
        }
        return response;
}

class Response {
    String message;
    String status;

    public Response() {
        // empty c-tor for serialization
    }

    public Response(String status, String message) {
        this.message = message;
        this.status = status;
    }
    // ... getters & setters omitted
    }

在 axios.post

的帮助下发送的 VueJs 端请求
var headers = {
            'Content-Type': 'application/json'
      }
      axios.post(`${API_URL.orderApi}`, formData, {headers})
        .then(response => {
          const commitPayload = response.data.message;
          const status        = response.data.status;
          if(status === 'Ok'){
              this.$store.commit('setMessage', commitPayload)
          }else{
              this.$store.commit('setErrMessage', commitPayload)
          }
          this.$router.push('/parts')
        },
        error => {
          this.$store.commit('setErrMessage', 'Submit Order failed')
          this.$router.push('/parts')
        })

Vue UI 客户端接收

Status Code: 406 Not Acceptable
Content-Type: text/html;charset=UTF-8
<html><head><title>Error</title></head><body>Not Acceptable</body></html>

为什么我可以用对象列表响应而不能用 POJO 响应,如何解决这个问题? 谢谢。

PS。项目依赖于 jackson-databind v2.8.2 和 spring v4.3.1

我从邮递员那里得到了正确的回复。我相信你有 getter 和 setter。

使用 header 接受:application/json

将 class 标记为可序列化的实现。

事实证明,我正在向映射到 url 且后缀 'htm' 的控制器发送带有 json 正文的 POST 请求。此请求导致与 mime-mapping 'text/html' 冲突,结果服务器立即响应代码 406。