關於SpringMVC的HttpMediaTypeNotSupportedException異常解決

weixin_33912246發表於2018-10-31

異常資訊

WARN  o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

1)使用post協議提交時,請檢查Content type型別,如:

$.ajax({
    type: "POST",
    contentType: "application/json;charset=UTF-8",
    url: "/reg",
    data: JSON.stringify(data.field),
    dataType: 'json',
    success: function(result) {
        if(result.code == 0) {
            layer.msg('註冊成功!');
        } else {
            layer.msg(result.msg);
        }
    }
});

請檢查上方contentType型別,如果想用springmvc @RequestBody註解做提交json字串自動繫結到pojo入參時,型別需要是"application/json;charset=UTF-8",否則會拋"not supported"異常。

2)缺少jackson-databind jar包

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

然後controller直接這麼用就好了:

@PostMapping("/reg")
public ResponseVo reg(@RequestBody user u) throws Exception {
       //其他業務
}

相關文章