HTTP Status 415 Unsupported Media Type [Spring MVC @RequestBody传递Json数据 ]

##1.错误信息

  1. 415 Unsupported Media Type
  2. The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

HTTP Status 415 Unsupported Media Type [Spring MVC @RequestBody传递Json数据 ]_第1张图片

##2.解决
###2.1.mvc:annotation-driven
spring-mvc-servlet.xml文件中增加对mvc:annotation-driven的配置,如下:


<mvc:annotation-driven />


<context:annotation-config/>

##2.2.pom.xml引入jackson包

<jackson.version>2.9.0jackson.version>


<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>${jackson.version}version>
dependency>
<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-coreartifactId>
    <version>${jackson.version}version>
dependency>
<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-annotationsartifactId>
    <version>${jackson.version}version>
dependency>

##2.3.$.ajax指定contentType

//@Requestbody只能处理非application/x-www-form-urlencoded格式的请求,
//所有需要指定其格式为application/json
$.ajax({
    type:"POST",
    url:url,
    data:JSON.stringify(
        {name:"张三",sex:"男"}
    ),
    contentType:"application/json; charset=utf-8",
    success:function (data) {
        console.log(data)
    }
});

##2.4.@RequestBody @ResponseBody
@RequestBody@ResponseBody都要有,@RequestBody用来将JSON字符串转化成POJO对象,后者将POJO对象转化成JSON字符串

    @PostMapping("/requestbody")
    @ResponseBody
    public String insert(@RequestBody User user, Model model){
        return "/requestannotation/requestbody";
    }

##2.5.result
HTTP Status 415 Unsupported Media Type [Spring MVC @RequestBody传递Json数据 ]_第2张图片

你可能感兴趣的:(Exception,Java-Web,Spring-MVC合集)