注意:此文章是我的原創,但願有轉載需要的朋友們標明文章出處,假設各位朋友們認爲寫的還好,就給個贊哈,你的鼓舞是我創做的最大動力,LinusZhu在此表示十分感謝,固然文章中若有紕漏,請聯繫linuszhu@163.com,敬請朋友們斧正,謝謝。javascript
這一部分主要解說SpringMVC怎樣處理Ajax請求,是首先要解說一下jackson類庫,可以幫助咱們在java對象和json、xml數據之間的互相轉換。他可以將控制器返回的對象直接轉換成json數據,供client使用,client也可以傳送json數據到server進行轉換,很是是方便。html
詳細環境搭建過程例如如下:java
1. 下載兩個jackson的jar包:web
jackson-core-asl-1.7.2jar、jackson-mapper-asl-1.7.2jarajax
2. 在SpringMVC配置文件里加入例如如下部分:spring
<mvc:annotation-driven /> <!-- 支持spring3.0新的mvc註解 -->json <!-- 啓動Spring MVC的註解功能,完畢請求和註解POJO的映射 -->mvc <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> app <property name="cacheSeconds" value="0" /> jsp <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> </list> </property> </bean> |
3. client代碼ajaxTest.jsp例如如下:
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Ajax</title> <META http-equiv="content-type" CONTENT="text/html;charset=UTF-8"> <script> function createAjaxObj() { var req; if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else { req = new ActiveXObject("Msxml2.XMLHTTP"); //ie } return req; } function sendAjaxReq() { var req = createAjaxObj(); req.open("get", "myajax.do?method=test1&uname=張三"); req.setRequestHeader("accept", "application/json"); req.onreadystatechange = function() { eval("var result=" + req.responseText); document.getElementById("div1").innerHTML = result[0].uname + "===" + result[1].uname + "===" + result[2].uname; }; req.send(null); } </script> </head> <body> <a href="javascript:void(0);" onclick="sendAjaxReq();">Ajax測試</a> <div id="div1"></div> </body> </html> |
4. server端代碼例如如下:
package com.spring.ajax; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.spring.bean.User; @Controller @RequestMapping("myajax.do") public class MyAjaxController { @RequestMapping(params = "method=test1") public @ResponseBody List<User> test1(String uname) throws Exception { String uname2 = new String(uname.getBytes("iso8859-1"), "gbk"); System.out.println(uname2); System.out.println("MyAjaxController.test1()"); List<User> list = new ArrayList<User>(); User u1 = new User(); u1.setId(111); u1.setUname("測試1"); User u2 = new User(); u2.setId(222); u2.setUname("測試2"); User u3 = new User(); u3.setId(333); u3.setUname("測試3"); list.add(u1); list.add(u2); list.add(u3); return list; } } |
5. 項目執行測試。
輸入地址:http://localhost:8081/SpringMVC02/ajaxTest.jsp ,界面例如如下:
點擊連接進行測試,會調用後臺程序,將結果返回到頁面上,例如如下: