ssm框架ajax发送数据报错Content type 'application/json' not supported

ajax代码:

var data = {
      "name":"aaa",
      "password":123
};

$.ajax({
      url:'/ems/test',
      data:JSON.stringify(data),
      type:'post',
      dataType:"json",
      contentType:'application/json;charset=utf-8',
      success:function(data){
            //其他逻辑
      }
})

controller代码:

@ResponseBody
@RequestMapping(value = "test",produces = "application/json";charset=utf-8")
public String test(@RequestBody Staff staff){
      //增删改查
}

首先解决这个错误需要在ajax代码中添加

dataType:"json",
contentType:'application/json;charset=utf-8',

然后再pom.xml中添加依赖

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.9</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.9</version>
        </dependency>

之后在springmvc.xml中加入配置

<!-- 设置json转换器 -->
    <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </bean>
    <!-- 设置string转换器 -->
    <bean id="stringConverter"
          class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="writeAcceptCharset" value="false" />

        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringConverter" />
                <ref bean="jsonConverter" />
            </list>
        </property>
    </bean>
posted @ 2020-08-10 09:13  sfencs  阅读(804)  评论(0编辑  收藏  举报