JavaWeb開發中Ajax技術、json與java實現List、Map資料直接傳遞的研究
一、在JavaWeb開發中基於jquery框架來使用ajax技術,Json與後臺servlet進行資料互動示例,下面示例中基於servlet技術,沒有使用struts2等框架。
由於專案需要通過ajax得到後臺的List物件、map物件裡面的值,閒暇時間摸索了一下關於json接受List物件的方法,步驟如下:
1.首先下載json所以依賴的包, Json-lib 最新版json-lib-2.3-jdk15.jar,其官方網站是:http://json-lib.sourceforge.net/可以直接download,細心的你會發現其網站頁面裡面有提示它還需要其他包:
Json-lib requires(at least) the following dependencies in your classpath:
•jakartacommons-lang 2.4
•jakartacommons-beanutils 1.7.0
•jakartacommons-collections 3.2
•jakartacommons-logging 1.1.1
•ezmorph 1.0.6
下載地址分別是:
http://commons.apache.org/beanutils/
http://commons.apache.org/collections/
http://commons.apache.org/logging/
http://ezmorph.sourceforge.net/
2.首先先見一個小web專案
先建一個User類:
package com.json; public class User { String username; String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
再建一個servlet 程式:
package com.json; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; public class TestJson extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String str= request.getParameter("name");//得到ajax傳遞過來的paramater System.out.print(str); PrintWriter out = response.getWriter(); List list = new ArrayList();//傳遞List Map m=new HashMap();//傳遞Map User u1=new User(); u1.setUsername("zah"); u1.setPassword("123"); User u2=new User(); u2.setUsername("ztf"); u2.setPassword("456"); list.add(u1); //新增User物件 list.add(u2); //新增User物件 m.put("u1", u1); m.put("u2", u2); JSONArray jsonArray2 = JSONArray.fromObject( list ); //把list轉化成轉化成json物件 JSONObject jo=JSONObject.fromObject(m);//轉化Map物件為Json物件 out.print(jsonArray2);//返給ajax請求 out.print(jo);//返給ajax請求 } } 配置好web.xml中的servlet對映,這一步就略了。
3.建立ajax實現 (這裡為了快速實現用的是jquery實現的)
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function test(){
$.ajax({
type:"POST", //請求方式
url:"testjson", //請求路徑:${base}/類所在的名稱空間/類名(配置檔案中執行對應類的那個name),名稱空間是在配置檔案中定義。
cache: false,
data:"name=zah", //傳參
dataType: 'json', //返回值型別
success:function(json){
alert(json[0].username+" " json[0].password); //彈出返回過來的List物件
}
});
}
</script>
</head>
<body>
<input type="button" name="b" value="測試" onclick=test()>
</body>
測試開始,點選按鈕彈出zah 123
json[0]就相當於u1物件 json[1]相當於u2物件,對於其屬性的訪問跟java物件一樣,其他的Connection測試應該一樣,訪問Map的話直接把返回函式改成如下即可:
success:function(json){
alert(json.u1.username)
}
直接跟上Key.屬性即可訪問Object物件。
後續會新增基於struts2框架的示例!
二、在JavaWeb開發中ajax+json+Struts2實現list傳遞例項講解:
1、首先需要下載JSON依賴的jar包。它主要是依賴如下:
json-lib-2.2.2-jdk15
ezmorph-1.0.4
commons-logging-1.0.4
commons-lang-2.4
commons-collections-3.2.1
commons-beanutils
2、例項。
2.1、身份證錯誤資訊Bean類(ErrorCondition.java)
**
*@Project: excel
*@Author: chenssy
*@Date: 2013-4-4
*@Copyright: chenssy All rights reserved.
*/
public class ErrorCondition {
private String name; // 姓名
private String idCard; // 身份證
private String status; // 錯誤狀態
private String message; // 錯誤資訊
ErrorCondition(String name,String idCard,String status,String message){
this.name = name;
this.idCard = idCard;
this.status = status;
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
2.2、JSP頁面(index.jsp)<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.7.2.js"></script>
</head>
<body>
<input type="button" value="點我顯示資料" id="clickMe">
<table id="showTable" border="1">
<tr>
<td>姓名</td>
<td>身份證</td>
<td>錯誤狀態</td>
<td>錯誤資訊</td>
</tr>
</table>
<script>
$("#clickMe").click( function(){
var url = "json/jsonTest.action";
$.ajax({
type:'get',
url:url,
dataType: 'json',
success:function(data){
$.each(data,function(i,list){
var _tr = $("<tr><td>"+list.name+"</td><td>"+
list.idCard+"</td><td>"+list.status+ "</td><td>"+list.message+"</td></tr>");
$("#showTable").append(_tr);
})
}
})
})
</script>
</body>
</html>
2.3、Action處理類(JsonTest_01.java)
/**
*@Project: jsonTest
*@Author: chenssy
*@Date: 2013-4-5
*@Copyright: chenssy All rights reserved.
*/
public class JsonTest_01 {
public String execute() throws IOException{
ErrorCondition r1 = new ErrorCondition("張三", "4306821989021611", "L", "長度錯誤");
ErrorCondition r2 = new ErrorCondition("李四", "430682198902191112","X", "校驗錯誤");
ErrorCondition r3 = new ErrorCondition("王五", "", "N", "身份證資訊為空");
List<ErrorCondition> list = new ArrayList<ErrorCondition>();
list.add(r1);
list.add(r2);
list.add(r3);
//將list轉化成JSON物件
JSONArray jsonArray = JSONArray.fromObject(list);
HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
response.setCharacterEncoding("UTF-8");
response.getWriter().print(jsonArray);
return null;
}
}
2.4、struts.xml配置
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<!-- 指定struts 2的配置檔案的跟元素 -->
<struts>
<package name="json" namespace="/json" extends="struts-default">
<action name="jsonTest" class="com.json.action.JsonTest_01" method="execute"></action>
</package>
</struts>
3、執行結果
開始頁面如下:
當點選按鈕後:
該博文轉載自:http://zah5897.iteye.com/blog/692038 和 http://www.jb51.net/article/35492.htm