1. 配置適配器並註冊json格式的轉換器,javascript
這裏適配器不可使用RequestMappingHandlerAdapter,(看老師的筆記用的就是RequestMappingHandlerApapter, 結果一直報錯)前端
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> </list> </property> </bean>
2. JsonTest主要代碼java
@Controller @RequestMapping("/json") public class JsonTest { @RequestMapping("/requestJson.do") public @ResponseBody User requestJson(@RequestBody User user) { System.out.println("user:" + user); return user; } }
3. 前端js代碼web
注意:此處必需要加上contentType:"application/json"才行ajax
<script type="text/javascript"> function requestJson(){ var json = {"userId":101,"userName":"zhangsan","age":23}; $.ajax({ type:"POST", url:"${pageContext.request.contextPath }/json/requestJson.do", /* data:JSON.stringify({ userId: 101, userName: "zhangsan", age: 23 }), */ data:'{"userId":101,"userName":"zhangsan","age":23}', contentType:"application/json;charset=utf-8", success:function(data){ alert(data); } }) } </script>
OK, 告一段落,相信請求和響應json數據的方法你已經會了.spring