SpringMVC接受JSON資料

楓葉梨花發表於2018-06-27

SpringMVC接收資料一般是新建一個VO物件接收,或者是使用@RequestParam或者@PathVariable接收引數格式,很少會後端接收一個JSON資料格式,不過也會出現,其實這個很簡單,只需要使用@RequestBody即可。

匯入Jar包

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.2</version>
</dependency>
複製程式碼

事例程式

JSONController.java

@ResponseBody
@RequestMapping(value="upjson", method = RequestMethod.POST)
public Book getJSONData(@RequestBody Book book){
	log.info("獲取到的資料為:"+book);
	book.setBookName("JavaJSON資料");
	return book;
}
複製程式碼

Book.java

public class Book {
    private String bookName;
    private Double price;
    
    public String getBookName() {
    	return bookName;
    }
    public void setBookName(String bookName) {
    	this.bookName = bookName;
    }
    public Double getPrice() {
    	return price;
    }
    public void setPrice(Double price) {
    	this.price = price;
    }
    @Override
    public String toString() {
    	return "Book [bookName=" + bookName + ", price=" + price + "]";
    }
}
複製程式碼

前端提交

<button onclick="upJSON()">點選傳輸JSON</button>

<script>
function upJSON(){
    $.ajax({
        type:'post',
        url:'${request.contextPath}/upjson',
        dataType:'json',
        contentType:"application/json;charset=UTF-8",
        data:JSON.stringify({"bookName":"Lucene","price":88.8}),
        async:false,
        error:function(result){
        	alert(result);
        },
        success:function(result){
        	alert(JSON.stringify(result))
        }
    });
}
</script>
複製程式碼

一般這樣可以實現,而且網上的資源也是這樣總結,不過我這邊還有點問題,這樣寫還是會一直報錯,不支援application/json;charset=UTF-8格式,出現org.springframework.web.HttpMediaTypeNotSupportedException異常。然後發現還需要在xml檔案中配置,才會正常。

配置

<bean id="mappingJacksonHttpMessageConverter"
  class="org.springframework.http.converter
            .json.MappingJackson2HttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
            <value>application/json;charset=UTF-8</value>
        </list>
    </property>
</bean>

<bean class="org.springframework.web.servlet.mvc.
            method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list >
            <ref bean="mappingJacksonHttpMessageConverter" />
        </list>
    </property>
</bean>
複製程式碼

如上配置就可以完美執行了。

相關文章