<!--注解適配器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> </list> </property> </bean> 注意:如果使用<mvc:annotation-driven />則不用定義上邊的內容。實現jsp頁面<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>在此處插入標題</title><script src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script><script type="text/Javascript"> // 請求json響應json function requestJsonByJson() { $.Ajax({ type : "post", url : "${pageContext.request.contextPath }/requestJsonByJson.action", contentType : "application/json;charset=utf-8", data : '{"name":"測試用戶","age":99}', success : function(data) { alert(data); } }); } // key=value請求響應json function requestJsonByKeyValue() { $.ajax({ type : "post", url : "${pageContext.request.contextPath }/requestJsonByKeyValue.action", //contentType默認是application/x-www-form-urlencoded//contentType : "application/json;charset=utf-8", data : 'name=測試用戶&age=99', success : function(data) { alert(data); } }); }</script></head><body> <input type="button" onclick="requestJsonByJson()" value="請求json響應json" /> <input type="button" onclick="requestJsonByKeyValue()" value="key=value請求響應json" /></body></html>Controller:@Controllerpublic class TestJsonController { // 提交json信息,響應json信息 @RequestMapping("/requestJsonByJson") public @ResponseBody UserCustom requestJsonByJson(@RequestBody UserCustom userCustom) throws Exception { return userCustom; } // 提交key value信息,響應json信息 @RequestMapping("/requestJsonByKeyValue") public @ResponseBody UserCustom requestJsonByKeyValue(@RequestBody UserCustom userCustom) throws Exception { return userCustom; }}
|
新聞熱點
疑難解答