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>
复制代码
如上配置就可以完美运行了。