小狼今天在测试springmvc中从json字符串自动转换成实体的技术时,出现问题
首先,小狼创建一个web项目,在lib目录下导入springmvc jar文件,这就不细说了,然后加入json支持类库
在webroo目录下加载jquery.js json2.js
jsp文件是这么写的:
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<script type="text/javascript" src="lib/jquery/jquery-1.4.2.js"></script>
<script type="text/javascript" src="lib/jquery/json2.js"></script>
<script type="text/javascript" src="js/sendAjax.js"></script>
</head>
<body>
This is my JSP page. <br>
<input type="button" οnclick="sendAjax2()" value="button2">
</body>
</html>
springMVC-servlet.xml
<context:component-scan base-package="qh.zcy.controller"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp"></bean>
sendAjax.js
function sendAjax2() {
//alert("test");
var userinfoRef = new userinfo("张臭臭", "zcy");
var jsonString = JSON.stringify(userinfoRef);
alert(jsonString);
//alert(jsonString);
$.ajax( {
type : "post",
url : "getJSONString2.zcy?t=" + new Date().getTime(),
data : jsonString
});
}
function userinfo(username, password) {
this.username = username;
this.password = password;
}
java控制器
@RequestMapping(value="getJSONString2",method=RequestMethod.POST)
public String getJsonString2(@RequestBody Userinfo userinfo){
System.out.println("test");
System.out.println(userinfo.getUsername()+" "+userinfo.getPassword());
return "index2";
}
运行,很快报错,("NetworkError: 415 Unsupported Media Type - http://localhost:8080/Springmvc_1/getJSONString2.zcy?t=1431859248389") 小狼找了半天,将sendAjax.js修改如下:
function sendAjax2() {
//alert("test");
var userinfoRef = new userinfo("张臭臭", "zcy");
var jsonString = JSON.stringify(userinfoRef);
alert(jsonString);
//alert(jsonString);
$.ajax( {
type : "post",
url : "getJSONString2.zcy?t=" + new Date().getTime(),
data : jsonString,
contentType : "application/json",
});
}
function userinfo(username, password) {
this.username = username;
this.password = password;
}
加上contentType : "application/json"。
可是,还是报同样的错误,问题来了,没有加上jackson-all-1.9.8.jar
加上之后还是报相同的错误,为什么呢,原来在springmvc-servlet.xml中加上一行<mvc:annotation-driven></mvc:annotation-driven>
什么原因呢??
首先 ,DefaultAnnotationHandlerMapping对象负责类级别的@RequestMapping注解,而AnnotationMethodHandlerAdapter负责方法级别的@RequestMapping注解,如果使用<mvc:annotation-driven></mvc:annotation-driven>注解,就会自动注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter两个bean。
其次,$.post()方法不设置contentType,他有默认的,但是我们要传递的是json类型的字符串。故而,改成$.ajax并设置contentType为application/json,另外,发送的请求内容不要转成json对象,直接发送json字符串即可
最后,也是最重要的,要添加jackson-all-1.9.8.jar jacksonJSON解析处理类库