JSON实例(AJAX+STRUTS )
前段时间做项目用到了json,今天我抽时间写了一个struts+ajax+json的例子.
个人感觉ajax+json在很大程度上降低了网络和服务器的IO,是一个很不错的组合!
1:json的lib我用的是json-lib-2.1-jdk15.jar,它可以在
2:struts用的是1.2
3:用到了js第三方prototype.js,主要用它包装的ajax对象,大家也没必要用这个,可以直接在js里用XMLHttpRequest。
以下是例子中所用到的相关文件:
Java代码
/////////////////////////////////////// toolhxw.js??
/**?
@hxw? 20080602?
*/?
//回调函数? 简单回调函数???
function showesay(dataResponse)??
{??
var data = eval('(' + dataResponse.responseText + ')');??
var str='';??
str+='<ul>';??
str+='<li>'+data.param1;+'</li>';??
str+='<li>'+data.param2;+'</li>';??
str+='</ul>';??
document.getElementById("content").innerHTML=str;??
}??
//回调函数? 复杂回调函数??
function showcomplex(dataResponse)??
{??
var data = eval('(' + dataResponse.responseText + ')');??
var str='';??
for(var i=0;i<data.js.length;i++)??
{???
str+='<ul>';??
str+='<li>'+data.js[i].id+'</li>';??
str+='<li>'+data.js[i].age+'</li>';??
str+='<li>'+data.js[i].name+'</li>';??
str+='<li>'+data.js[i].address+'</li>';??
str+='</ul>';??
}??
document.getElementById("content").innerHTML=str;??
}??
//获取简单的json数据??
function getesay(){??
var url = 'test.do';??
? var pars = 'method=getEasy';??
? var ajax = new Ajax.Request(??
?? url,??
?? {method:'post',parameters:pars,onComplete:showesay}??
? );????
}??
//获取对象级复杂数据??
function getcomplex(){??
var url = 'test.do';??
? var pars = 'method=getComplex';??
? var ajax = new Ajax.Request(??
?? url,??
?? {method:'post',parameters:pars,onComplete:showcomplex}??
? );????
}??
?
///////////////////////////////////////struts-config.xml??
?
<?xml version="1.0" encoding="UTF-8"?>??
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">??
?
<struts-config>??
? <data-sources />??
? <form-beans />??
? <global-exceptions />??
? <global-forwards />??
? <action-mappings >??
??? <action path="/test" parameter="method" type="com.json.struts.action.TestAction">??
?? </action>??
??????
? </action-mappings>??
?
? <message-resources parameter="com.json.struts.ApplicationResources" />??
</struts-config>??
?
////////////////////////////////TestAction.java??
?
/*?
* Generated by MyEclipse Struts?
* Template path: templates/java/JavaClass.vtl?
*/?
package com.json.struts.action;??
?
import java.io.PrintWriter;??
?
import javax.servlet.http.HttpServletRequest;??
import javax.servlet.http.HttpServletResponse;??
import org.apache.struts.action.ActionForm;??
import org.apache.struts.action.ActionForward;??
import org.apache.struts.action.ActionMapping;??
import org.apache.struts.actions.DispatchAction;??
import net.sf.json.*;??
?
/**?
* @author hxw?
*?
*/?
public class TestAction extends DispatchAction {??
???
?
/**?
? * 获取简单组合数据?
? */?
public ActionForward getEasy(ActionMapping mapping, ActionForm form,??
?? HttpServletRequest request, HttpServletResponse response) {??
? response.setContentType("text/html; charset=GBK");??
? try?
? {??
?? PrintWriter out = response.getWriter();??
?? //这里的数据拼装一般是从数据库查询来的??
?? JSONObject jsonObject = new JSONObject();??
????? jsonObject.put("param1", "变量一");??
????? jsonObject.put("param2", "变量二");??
?? out.print(jsonObject.toString());??
?? out.flush();??
?? out.close();??
?? return null;??
? }catch(Exception e)??
? {??
?? e.printStackTrace();??
?? return null;??
? }??
? }??
/**?
? * 获取复杂组合数据?
? */?
public ActionForward getComplex(ActionMapping mapping, ActionForm form,??
?? HttpServletRequest request, HttpServletResponse response) {??
? response.setContentType("text/html; charset=GBK");??
? try?
? {??
?? PrintWriter out = response.getWriter();??
?? JSONObject obj = new JSONObject();??
?? JSONArray js = new JSONArray();??
?? //这里的数据拼装一般是从数据库查询来的??
??? for(int i=0;i<3;i++)??
??? {??
???? JSONObject objtemp = new JSONObject();??
???? objtemp.put("id", i);??
???? objtemp.put("age", "23");??
???? objtemp.put("name", "test"+i);??
???? objtemp.put("address", "test");??
???? js.add(objtemp);??
??? }??
?? obj.put("js",js);??
???????? out.print(obj.toString());??
? }catch(Exception e)??
? {??
?? e.printStackTrace();??
?? System.out.print("消费明细json存储异常");??
? }??
? return null;??
}??
}??
?
////////////////////////////test.jsp??
<%@ page language="java" import="java.util.*" contentType="text/html;charset=gbk"%>??
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">??
<html>??
? <head>??
??? <title>json练习</title>??
??????
<meta http-equiv="pragma" content="no-cache">??
<meta http-equiv="cache-control" content="no-cache">??
<meta http-equiv="expires" content="0">??????
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">??
<meta http-equiv="description" content="This is my page">??
<script type="text/javascript"? src="js/prototype.js"></script>??
??? <script type="text/javascript"? src="js/toolhxw.js"></script>??
??? </head>??
????
? <body>??
? <div id="func" >??
? <a href='javascript:getesay()'>获取简单组合数据</a>??
? <a href='javascript:getcomplex()'>获取复杂组合数据</a>??
? </div>??
??? <div id="content">??
??? 正在获取内容...??
??? </div>??
? </body>??
</html>?
/////////////////////////////////////// toolhxw.js
/**
@hxw? 20080602
*/
//回调函数? 简单回调函数
function showesay(dataResponse)
{
var data = eval('(' + dataResponse.responseText + ')');
var str='';
str+='<ul>';
str+='<li>'+data.param1;+'</li>';
str+='<li>'+data.param2;+'</li>';
str+='</ul>';
document.getElementById("content").innerHTML=str;
}
//回调函数? 复杂回调函数
function showcomplex(dataResponse)
{
var data = eval('(' + dataResponse.responseText + ')');
var str='';
for(var i=0;i<data.js.length;i++)
{
str+='<ul>';
str+='<li>'+data.js[i].id+'</li>';
str+='<li>'+data.js[i].age+'</li>';
str+='<li>'+data.js[i].name+'</li>';
str+='<li>'+data.js[i].address+'</li>';
str+='</ul>';
}
document.getElementById("content").innerHTML=str;
}
//获取简单的json数据
function getesay(){
var url = 'test.do';
? var pars = 'method=getEasy';
? var ajax = new Ajax.Request(
?? url,
?? {method:'post',parameters:pars,onComplete:showesay}
? );?
}
//获取对象级复杂数据
function getcomplex(){
var url = 'test.do';
? var pars = 'method=getComplex';
? var ajax = new Ajax.Request(
?? url,
?? {method:'post',parameters:pars,onComplete:showcomplex}
? );?
}
///////////////////////////////////////struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
? <data-sources />
? <form-beans />
? <global-exceptions />
? <global-forwards />
? <action-mappings >
??? <action path="/test" parameter="method" type="com.json.struts.action.TestAction">
?? </action>
???
? </action-mappings>
? <message-resources parameter="com.json.struts.ApplicationResources" />
</struts-config>
////////////////////////////////TestAction.java
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.json.struts.action;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import net.sf.json.*;
/**
* @author hxw
*
*/
public class TestAction extends DispatchAction {
/**
? * 获取简单组合数据
? */
public ActionForward getEasy(ActionMapping mapping, ActionForm form,
?? HttpServletRequest request, HttpServletResponse response) {
? response.setContentType("text/html; charset=GBK");
? try
? {
?? PrintWriter out = response.getWriter();
?? //这里的数据拼装一般是从数据库查询来的
?? JSONObject jsonObject = new JSONObject();
????? jsonObject.put("param1", "变量一");
????? jsonObject.put("param2", "变量二");
?? out.print(jsonObject.toString());
?? out.flush();
?? out.close();
?? return null;
? }catch(Exception e)
? {
?? e.printStackTrace();
?? return null;
? }
? }
/**
? * 获取复杂组合数据
? */
public ActionForward getComplex(ActionMapping mapping, ActionForm form,
?? HttpServletRequest request, HttpServletResponse response) {
? response.setContentType("text/html; charset=GBK");
? try
? {
?? PrintWriter out = response.getWriter();
?? JSONObject obj = new JSONObject();
?? JSONArray js = new JSONArray();
?? //这里的数据拼装一般是从数据库查询来的
??? for(int i=0;i<3;i++)
??? {
???? JSONObject objtemp = new JSONObject();
???? objtemp.put("id", i);
???? objtemp.put("age", "23");
???? objtemp.put("name", "test"+i);
???? objtemp.put("address", "test");
???? js.add(objtemp);
??? }
?? obj.put("js",js);
???????? out.print(obj.toString());
? }catch(Exception e)
? {
?? e.printStackTrace();
?? System.out.print("消费明细json存储异常");
? }
? return null;
}
}
////////////////////////////test.jsp
<%@ page language="java" import="java.util.*" contentType="text/html;charset=gbk"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
? <head>
??? <title>json练习</title>
???
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">???
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript"? src="js/prototype.js"></script>
??? <script type="text/javascript"? src="js/toolhxw.js"></script>
??? </head>
?
? <body>
? <div id="func" >
? <a href='javascript:getesay()'>获取简单组合数据</a>
? <a href='javascript:getcomplex()'>获取复杂组合数据</a>
? </div>
??? <div id="content">
??? 正在获取内容...
??? </div>
? </body>
</html>
大家将这几个文件拷贝到你的myeclipse的web项目中,发布运行即可。
个人感觉ajax+json在很大程度上降低了网络和服务器的IO,是一个很不错的组合!
1:json的lib我用的是json-lib-2.1-jdk15.jar,它可以在
2:struts用的是1.2
3:用到了js第三方prototype.js,主要用它包装的ajax对象,大家也没必要用这个,可以直接在js里用XMLHttpRequest。
以下是例子中所用到的相关文件:
Java代码
/////////////////////////////////////// toolhxw.js??
/**?
@hxw? 20080602?
*/?
//回调函数? 简单回调函数???
function showesay(dataResponse)??
{??
var data = eval('(' + dataResponse.responseText + ')');??
var str='';??
str+='<ul>';??
str+='<li>'+data.param1;+'</li>';??
str+='<li>'+data.param2;+'</li>';??
str+='</ul>';??
document.getElementById("content").innerHTML=str;??
}??
//回调函数? 复杂回调函数??
function showcomplex(dataResponse)??
{??
var data = eval('(' + dataResponse.responseText + ')');??
var str='';??
for(var i=0;i<data.js.length;i++)??
{???
str+='<ul>';??
str+='<li>'+data.js[i].id+'</li>';??
str+='<li>'+data.js[i].age+'</li>';??
str+='<li>'+data.js[i].name+'</li>';??
str+='<li>'+data.js[i].address+'</li>';??
str+='</ul>';??
}??
document.getElementById("content").innerHTML=str;??
}??
//获取简单的json数据??
function getesay(){??
var url = 'test.do';??
? var pars = 'method=getEasy';??
? var ajax = new Ajax.Request(??
?? url,??
?? {method:'post',parameters:pars,onComplete:showesay}??
? );????
}??
//获取对象级复杂数据??
function getcomplex(){??
var url = 'test.do';??
? var pars = 'method=getComplex';??
? var ajax = new Ajax.Request(??
?? url,??
?? {method:'post',parameters:pars,onComplete:showcomplex}??
? );????
}??
?
///////////////////////////////////////struts-config.xml??
?
<?xml version="1.0" encoding="UTF-8"?>??
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">??
?
<struts-config>??
? <data-sources />??
? <form-beans />??
? <global-exceptions />??
? <global-forwards />??
? <action-mappings >??
??? <action path="/test" parameter="method" type="com.json.struts.action.TestAction">??
?? </action>??
??????
? </action-mappings>??
?
? <message-resources parameter="com.json.struts.ApplicationResources" />??
</struts-config>??
?
////////////////////////////////TestAction.java??
?
/*?
* Generated by MyEclipse Struts?
* Template path: templates/java/JavaClass.vtl?
*/?
package com.json.struts.action;??
?
import java.io.PrintWriter;??
?
import javax.servlet.http.HttpServletRequest;??
import javax.servlet.http.HttpServletResponse;??
import org.apache.struts.action.ActionForm;??
import org.apache.struts.action.ActionForward;??
import org.apache.struts.action.ActionMapping;??
import org.apache.struts.actions.DispatchAction;??
import net.sf.json.*;??
?
/**?
* @author hxw?
*?
*/?
public class TestAction extends DispatchAction {??
???
?
/**?
? * 获取简单组合数据?
? */?
public ActionForward getEasy(ActionMapping mapping, ActionForm form,??
?? HttpServletRequest request, HttpServletResponse response) {??
? response.setContentType("text/html; charset=GBK");??
? try?
? {??
?? PrintWriter out = response.getWriter();??
?? //这里的数据拼装一般是从数据库查询来的??
?? JSONObject jsonObject = new JSONObject();??
????? jsonObject.put("param1", "变量一");??
????? jsonObject.put("param2", "变量二");??
?? out.print(jsonObject.toString());??
?? out.flush();??
?? out.close();??
?? return null;??
? }catch(Exception e)??
? {??
?? e.printStackTrace();??
?? return null;??
? }??
? }??
/**?
? * 获取复杂组合数据?
? */?
public ActionForward getComplex(ActionMapping mapping, ActionForm form,??
?? HttpServletRequest request, HttpServletResponse response) {??
? response.setContentType("text/html; charset=GBK");??
? try?
? {??
?? PrintWriter out = response.getWriter();??
?? JSONObject obj = new JSONObject();??
?? JSONArray js = new JSONArray();??
?? //这里的数据拼装一般是从数据库查询来的??
??? for(int i=0;i<3;i++)??
??? {??
???? JSONObject objtemp = new JSONObject();??
???? objtemp.put("id", i);??
???? objtemp.put("age", "23");??
???? objtemp.put("name", "test"+i);??
???? objtemp.put("address", "test");??
???? js.add(objtemp);??
??? }??
?? obj.put("js",js);??
???????? out.print(obj.toString());??
? }catch(Exception e)??
? {??
?? e.printStackTrace();??
?? System.out.print("消费明细json存储异常");??
? }??
? return null;??
}??
}??
?
////////////////////////////test.jsp??
<%@ page language="java" import="java.util.*" contentType="text/html;charset=gbk"%>??
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">??
<html>??
? <head>??
??? <title>json练习</title>??
??????
<meta http-equiv="pragma" content="no-cache">??
<meta http-equiv="cache-control" content="no-cache">??
<meta http-equiv="expires" content="0">??????
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">??
<meta http-equiv="description" content="This is my page">??
<script type="text/javascript"? src="js/prototype.js"></script>??
??? <script type="text/javascript"? src="js/toolhxw.js"></script>??
??? </head>??
????
? <body>??
? <div id="func" >??
? <a href='javascript:getesay()'>获取简单组合数据</a>??
? <a href='javascript:getcomplex()'>获取复杂组合数据</a>??
? </div>??
??? <div id="content">??
??? 正在获取内容...??
??? </div>??
? </body>??
</html>?
/////////////////////////////////////// toolhxw.js
/**
@hxw? 20080602
*/
//回调函数? 简单回调函数
function showesay(dataResponse)
{
var data = eval('(' + dataResponse.responseText + ')');
var str='';
str+='<ul>';
str+='<li>'+data.param1;+'</li>';
str+='<li>'+data.param2;+'</li>';
str+='</ul>';
document.getElementById("content").innerHTML=str;
}
//回调函数? 复杂回调函数
function showcomplex(dataResponse)
{
var data = eval('(' + dataResponse.responseText + ')');
var str='';
for(var i=0;i<data.js.length;i++)
{
str+='<ul>';
str+='<li>'+data.js[i].id+'</li>';
str+='<li>'+data.js[i].age+'</li>';
str+='<li>'+data.js[i].name+'</li>';
str+='<li>'+data.js[i].address+'</li>';
str+='</ul>';
}
document.getElementById("content").innerHTML=str;
}
//获取简单的json数据
function getesay(){
var url = 'test.do';
? var pars = 'method=getEasy';
? var ajax = new Ajax.Request(
?? url,
?? {method:'post',parameters:pars,onComplete:showesay}
? );?
}
//获取对象级复杂数据
function getcomplex(){
var url = 'test.do';
? var pars = 'method=getComplex';
? var ajax = new Ajax.Request(
?? url,
?? {method:'post',parameters:pars,onComplete:showcomplex}
? );?
}
///////////////////////////////////////struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
? <data-sources />
? <form-beans />
? <global-exceptions />
? <global-forwards />
? <action-mappings >
??? <action path="/test" parameter="method" type="com.json.struts.action.TestAction">
?? </action>
???
? </action-mappings>
? <message-resources parameter="com.json.struts.ApplicationResources" />
</struts-config>
////////////////////////////////TestAction.java
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.json.struts.action;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import net.sf.json.*;
/**
* @author hxw
*
*/
public class TestAction extends DispatchAction {
/**
? * 获取简单组合数据
? */
public ActionForward getEasy(ActionMapping mapping, ActionForm form,
?? HttpServletRequest request, HttpServletResponse response) {
? response.setContentType("text/html; charset=GBK");
? try
? {
?? PrintWriter out = response.getWriter();
?? //这里的数据拼装一般是从数据库查询来的
?? JSONObject jsonObject = new JSONObject();
????? jsonObject.put("param1", "变量一");
????? jsonObject.put("param2", "变量二");
?? out.print(jsonObject.toString());
?? out.flush();
?? out.close();
?? return null;
? }catch(Exception e)
? {
?? e.printStackTrace();
?? return null;
? }
? }
/**
? * 获取复杂组合数据
? */
public ActionForward getComplex(ActionMapping mapping, ActionForm form,
?? HttpServletRequest request, HttpServletResponse response) {
? response.setContentType("text/html; charset=GBK");
? try
? {
?? PrintWriter out = response.getWriter();
?? JSONObject obj = new JSONObject();
?? JSONArray js = new JSONArray();
?? //这里的数据拼装一般是从数据库查询来的
??? for(int i=0;i<3;i++)
??? {
???? JSONObject objtemp = new JSONObject();
???? objtemp.put("id", i);
???? objtemp.put("age", "23");
???? objtemp.put("name", "test"+i);
???? objtemp.put("address", "test");
???? js.add(objtemp);
??? }
?? obj.put("js",js);
???????? out.print(obj.toString());
? }catch(Exception e)
? {
?? e.printStackTrace();
?? System.out.print("消费明细json存储异常");
? }
? return null;
}
}
////////////////////////////test.jsp
<%@ page language="java" import="java.util.*" contentType="text/html;charset=gbk"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
? <head>
??? <title>json练习</title>
???
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">???
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript"? src="js/prototype.js"></script>
??? <script type="text/javascript"? src="js/toolhxw.js"></script>
??? </head>
?
? <body>
? <div id="func" >
? <a href='javascript:getesay()'>获取简单组合数据</a>
? <a href='javascript:getcomplex()'>获取复杂组合数据</a>
? </div>
??? <div id="content">
??? 正在获取内容...
??? </div>
? </body>
</html>
大家将这几个文件拷贝到你的myeclipse的web项目中,发布运行即可。