记录
今晚解决了一个坑了我一个下午的问题:Spring MVC中接收和发送JSON数据.
PS:其中很多的失误是自己一直解决不了着急造成的.
解决的过程与其中遇到的问题
首先建立一个Spring MVC的项目,然后配置各种东西,这里就不详细说明了。
第一个坑点
第一个坑点就是配置Spring时用idea,一路回车,然后就错了,然后在网上找到解决的办法了。错误如下:
通配符的匹配很全面, 但无法找到元素 ‘mvc:annotation-driven’ 的声明。
下面的是错误的:
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:mvc=”http://www.springframework.org/schema/tool”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
** http://www.springframework.org/schema/tool
http://www.springframework.org/schema/tool/spring-tool.xsd“**>
下面的这个是正确的:
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:mvc=”http://www.springframework.org/schema/mvc”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
* http://www.springframework.org/schema/mvc *
* http://www.springframework.org/schema/mvc/spring-mvc.xsd“*>
为什么会出现这个错误的呢?这是因为在上面那个错误的配置下的mvc他又一个<mvc:annotation />
标签,所以就。。。
第二个坑点
遇到的第二个坑点是以前从未遇到的Http 415 :不支持的媒体类型
这就是因为在网上不断的找,然后不断的该,然后就415了.其实正真好的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 下面的这一行,会让Spring自动注册RequestMappingHandlerAdapter和RequestMappingHandlerAdapter,然后就支持JSON了 -->
<mvc:annotation-driven />
<!-- 下面的这句话是让默认的Servlet拦截静态资源,否则加载静态资源就会404 -->
<mvc:default-servlet-handler />
<mvc:resources mapping="/**/*.js" location="/" />
<context:component-scan base-package="com.example.controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/content/"
p:suffix=".jsp" />
</beans>
这里用到的是一个Spring MVC的转换器:MappingJackson2HttpMessageConverter,所以需要使用jackson-databind,jackson-core,和其它几个Jar包,但是不幸的是我一直找的是这种的
但是最后发现这在最新的Spring中不能用,真是… 会报各种Bug,中间还有堆栈溢出
正确的应该是下面的:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
</dependency>
下面的是Controller:
import com.example.domain.Person;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@Controller
@RequestMapping("/json")
public class BookController {
private static final Logger logger = Logger.getLogger(BookController.class);
@RequestMapping(value = "/testRequestBody", method = POST,consumes = "application/json") // 这里必须使用@RequestBody
public void setJson(@RequestBody Person person, HttpServletResponse response) throws IOException {
ObjectMapper mapper = new ObjectMapper();
person.setName("李四");
person.setSex("男");
System.out.println(mapper.writeValueAsString(person));
response.getWriter().println(mapper.writeValueAsString(person));
}
}
这个是发送的AJAX:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>测试JSON传输</title>
<script type="text/javascript" src="/Js/jquery-3.3.1.min.js" ></script>
<script type="text/javascript" src="Js/json2.js" ></script>
<script type="text/javascript">
function testRequestBody(){
$.ajax("${pageContext.request.contextPath}/json/testRequestBody"
{
dataType : "json",
type : "post",
contentType:"application/json",
data:JSON.stringify({"id" : 1, "name" : "张三"}),
async: true ,
success :function(data){
console.log(data);
$("#id").html(data.id);
$("#name").html(data.name);
$("#sex").html(data.sex);
},
// 请求出错时调用的函数
error:function(){
alert("数据发送失败");
}
});
}
</script>
</head>
<body>
<p>
编号:<span id="id"></span><br>
姓名:<span id="name"></span><br>
性别:<span id="sex"></span><br></p>
<button onclick="testRequestBody()" >发送</button>
</body>
</html>
也可以使用Postman测试.
使用Postman测试,
第一步填写URL:
第二步填写Header的COntent-type:application
第三步填写Body.
还有一个坑定比较弱智,这里就不单独写了,在写Person类的时候忘了写无参构造器,然后就一直400,就是下图:400,一般400就是参数的问题,两边没有交接好
PS:上图是在Postman截的,然后就有乱码的现象.
来一张最后的结果图: