在java中使用json数据需导入相应的jar包,即将相应的jar包复制到Web工程下 WebRoot–>WEB-INF–>lib文件夹中,相应的jar包为以下几个:
下载地址:
1. Download json-lib(https://sourceforge.net/projects/json-lib/files/json-lib/)
2. Download ezmorph(https://sourceforge.net/projects/ezmorph/files/)
3. Download commons-logging(http://commons.apache.org/logging/download_logging.cgi)
4. Download commons-lang(http://commons.apache.org/lang/download_lang.cgi)
5. Download commons-collections(http://commons.apache.org/collections/download_collections.cgi)
6. Download commons-beanutils(http://commons.apache.org/beanutils/download_beanutils.cgi)
不想一个个分别去下载的,在这里下载。
前端js中:
function getFormData()
{
var json =
{
"username" : document.getElementById("username").value
, "pwd" : document.getElementById("pwd").value
};
return json;
}
function post()
{
$.getJSON("./JsonTestServlet", {jsonData: JSON.stringify(getFormData())}, function(jsonData)
{
alert(JSON.stringify(jsonData));
alert(jsonData[0].username);
alert(jsonData[0].pwd);
});
}
前端先将表单数据封装成json数据,再采用jquery封装的ajax技术传送json数据。
后台java中:
JSONObject jsonData = JSONObject.fromObject(request.getParameter("jsonData")); //获取前端的jsonData
JSONArray jsonArray = new JSONArray();
String username = jsonData.getString("username"); // 获得前端传来的用户名
while (rs.next())
{
JSONObject temp = new JSONObject().element("username", rs.getString("user")).element("pwd", rs.getString("pwd")); // 创建临时json对象
jsonArray.add(temp); //将该json对象添加到jsonArray中
}
out.print(jsonArray.toString()); //将jsonArray对象传到前端
参考资料
[1] JSON.parse()和JSON.stringify()(http://blog.youkuaiyun.com/wangxiaohu__/article/details/7254598)
[2] JSONObject put,accumulate,element的区别(http://ljhzzyx.blog.163.com/blog/static/3838031220126810430157/)