1. 程式人生 > >SpringMVC接收前端json資料問題

SpringMVC接收前端json資料問題

1.後臺POJO類接收前端資料,Integer型別屬性資料接收不到

POJO類:
public class User {

    private String username;
    private Integer age;
    private String address;

	getter/setter方法
}

前端:

 $("#showTooltips").click(function() {
        var formObject = {};
        var formArray =$("#userInfo").serializeArray();
        $.each(formArray,function(i,item){
            formObject[item.name] = item.value;
        });
        $.ajax({
            url:"user/addUser",
            type:"post",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(formObject),
            dataType: "json",
            success:function(data){
                alert(data.msg);
            },
            error:function(e){
                alert("錯誤!!");
            }
        });
    });

後臺接收:

@RequestMapping(value = "/addUser", method =RequestMethod.POST)
    @ResponseBody
    public JSONObject addUser(@RequestBody User user) {
        JSONObject jsonObject = new JSONObject();
        if(user.getUsername() == null) {
            jsonObject.put("msg", "新增人員失敗");
        } else {
            jsonObject.put("msg", "新增人員成功");
        }
        return jsonObject;
    }

因為在springmvc配置檔案中

<!--避免IE執行AJAX時,返回JSON出現下載檔案 -->  
<bean id="mappingJacksonHttpMessageConverter"  
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
    <property name="supportedMediaTypes">  
        <list>  
            <value>text/html;charset=UTF-8</value>  
        </list>  
    </property>  
</bean>  

解決方法:
Spring4.1.1去掉了MappingJacksonHttpMessageConverter

spring-mvc配置將MappingJacksonHttpMessageConverter改成MappingJackson2HttpMessageConverter,

Maven對org.codehaus.jackson的引用,改用 com.fasterxml.jackson.core

MappingJacksonHttpMessageConverter這個類是過時的,

配置檔案改為

<!--避免IE執行AJAX時,返回JSON出現下載檔案 -->
    <bean id="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

pom.xml

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