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

时间:2019-01-18 18:40:51

标签: json spring-mvc vue.js jackson jackson-databind

I have no trouble to send list of objects in response on POST request and receive it in VueJs client

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

But when I try to response with custom class Response (I even added produces="application/json" in RequestMapping annotation )

@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
    }

On VueJs side request sent with help of axios.post

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 client receive

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

Why I can respond with list of object and can't respond with POJO and how to fix the issue? Thank you.

PS. Project depends on jackson-databind v2.8.2 and spring v4.3.1

2 个答案:

答案 0 :(得分:0)

当我从邮递员那里得到答复时,我可以正确地得到答复。我相信您有吸气剂和吸气剂。

使用标头接受:application / json

将类标记为实现可序列化。

答案 1 :(得分:0)

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