使用maven管理项目依赖,引入json需要增加如下jar包:
<!-- Json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
servlet使用例子:
/**
* curl -d "" http://localhost:8080/JavaWeb/queryaccount <br/>
* <br/>
* [{id:1,name:张三},{id:2,name:LucyLi}]
*/
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 7927614586396190782L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletContext sc = getServletContext();
Connection conn = (Connection) sc.getAttribute("CONNECTION");
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement("select id,name from account");
rs = stmt.executeQuery();
resp.setContentType("application/x-javascript;charset=utf-8");
PrintWriter out = resp.getWriter();
StringBuffer json = new StringBuffer();
json.append("[");
while(rs.next()) {
json.append("{");
json.append("\"id\":\"").append(rs.getString("id")).append("\",");
json.append("\"name\":\"").append(rs.getString("name")).append("\"");
json.append("},");
}
json.deleteCharAt(json.length() - 1);
json.append("]");
out.println(json.toString());
out.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs!=null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(stmt!=null)
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
resp.setContentType("application/x-javascript;charset=utf-8");
PrintWriter out = resp.getWriter();
StringBuffer json = new StringBuffer();
json.append("[");
while(rs.next()) {
json.append("{");
json.append("\"id\":\"").append(rs.getString("id")).append("\",");
json.append("\"name\":\"").append(rs.getString("name")).append("\"");
json.append("},");
}
json.deleteCharAt(json.length() - 1);
json.append("]");
out.println(json.toString());
out.close();
使用resultset直接生成json串:
public class JsonUtils {
public static String resultSetToJson(ResultSet rs)
throws SQLException, JSONException {
JSONArray array = new JSONArray();
//获取列数
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
while(rs.next()) {
JSONObject jsonObj = new JSONObject();
for(int i=0; i<columns; i++) {
String columnName = metaData.getColumnLabel(i+1);
String value = rs.getString(columnName);
jsonObj.put(columnName, value);
}
array.put(jsonObj);
}
return array.toString();
}
}
具体调用如下:
stmt = conn.prepareStatement("select title,id from bookinfo");
rs = stmt.executeQuery();
resp.setContentType("application/x-javascript;charset=utf-8");
PrintWriter out = resp.getWriter();
String json;
try {
json = JsonUtils.resultSetToJson(rs);
out.println(json);
} catch (JSONException e) {
e.printStackTrace();
} finally{
out.close();
}
使用javabeen,调用 toJSONObject.
使用httprequest对象来实现ajax请求,将获得的内容添加到select中:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Buy Page</title>
<script type="text/javascript">
<!--
window.onload= function() {
loadRequest("querybook","book");
sendRequestUser("queryaccount");
}
var xmlhttp;
function createXMLHttpRequest() {
//基于Mozilla的浏览器
if(window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXOject) { //IE浏览器
var msxmls = ["MSXML3","MSXML2","Microsoft"];
for (var i=0; i< msxmls.length; i++) {
try {
return new ActiveXObject(msxmls[i]+".XMLHTTP");
} catch (e) {
}
}
}
}
function loadRequest(url,selectId) {
var xmlhttp1 = createXMLHttpRequest();
xmlhttp1.open("POST",url,true);
xmlhttp1.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp1.onreadystatechange= function() {
if(xmlhttp1.readyState!=4) return;
if(xmlhttp1.status!=200){
alert("Problem retrieving XML data");
return;
}
var list=eval('('+xmlhttp1.responseText+')');
var users = document.getElementById(selectId);
if(list.length>0){
for(var i=0;i<list.length;i++) {
var op = new Option(list[i].title,list[i].id);
users.add(op);
}
}
};
xmlhttp1.send(null);
}
function sendRequestUser(url) {
xmlhttp = createXMLHttpRequest();
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.onreadystatechange= function() {
processResponseUser(xmlhttp);
};
xmlhttp.send(null);
}
function processResponseUser(xmlhttp) {
if(xmlhttp.readyState!=4) return;
if(xmlhttp.status!=200){
alert("Problem retrieving XML data");
return;
}
var list=eval('('+xmlhttp.responseText+')');
var users = document.getElementById("user");
if(list.length>0){
for(var i=0;i<list.length;i++) {
var op = new Option(list[i].name,list[i].id);
users.add(op);
}
}
}
//-->
</script>
</head>
<body>
<form action="trade" method="post">
书名<select id="book" name="book"></select><br/>
用户<select id="user" name="user"></select><br/>
输入购买数量<input type="text" id="amount" name="amount"><br/>
<input type="reset" value="重填">
<input type="submit" value="购买">
</form>
</body>
</html>