第四章 AJAX实例

将集合解析为JSON数据类型传回
需要用到插件包为:
Json-lib
此包又用到下面的五个包开源项目包,
jakarta commons-lang 2.4
jakarta commons-beanutils 1.7.0
jakarta commons-collections 3.2
jakarta commons-logging 1.1.1
ezmorph 1.0.6
所以我们得准备六个包

示例:
MODEL类:
public class Student {
private String uname;
private int age;
private String address;

public Student() {
}

public Student(String uname, int age, String address) {
super();
this.uname = uname;
this.age = age;
this.address = address;
}

public String getUname() {
return uname;
}

public void setUname(String uname) {
this.uname = uname;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}
}

package chapter4.action;

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 JSONServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Student> list = new ArrayList<Student>();
list.add(new Student("张三", 22, "武汉"));
list.add(new Student("李四", 22, "武汉"));
list.add(new Student("王五", 22, "武汉"));
list.add(new Student("赵六", 22, "武汉"));

String back_val = JSONArray.fromObject(list).toString();
PrintWriter out = response.getWriter();
out.print(back_val);
out.flush();
out.close();
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

<%@page contentType="text/html; charset=utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="basePath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>POST方式传值</title>
<script type="text/javascript" src="${basePath}/script/my.js"></script>
<script type="text/javascript" src="${basePath}/script/json2.js"></script>
<script type="text/javascript">
function sendJSON() {
var xmlHttp = null;
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("您的浏览器不支持AJAX");
return;
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var back_val = xmlHttp.responseText;
var students = eval('(' + back_val + ')');
var table = "<table border='1'>";
for(var i=0; i<students.length; i++){
table += "<tr>";
table += "<td>";
table += students[i].uname;
table += "</td>";
table += "<td>";
table += students[i].age;
table += "</td>";
table += "<td>";
table += students[i].address;
table += "</td>";
table += "</tr>";
}
table += "</table>";
}
document.getElementById("msg").innerHTML = table;
};
xmlHttp.open("GET", "${basePath}/JSONServlet?time="
+ new Date().getTime());
xmlHttp.send(null);
}
</script>
</head>
<body onload="sendJSON()">
<div id="msg"></div>
</body>
</html>

自动提示示例:
<%@page contentType="text/html; charset=utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="basePath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>POST方式传值</title>
<style>
#word {
width: 150px;
}

#tip {
position: absolute;
top: 0px;
left: 0px;
width: 154px;
font-size: 12px;
}

.mouseOut {
color: #000000;
background-color: #FFFFFF;
}

.mouseOver {
color: #FFFFFF;
background-color: #0000FF;
}
</style>
<script type="text/javascript" src="${basePath}/script/my.js"></script>
<script type="text/javascript" src="${basePath}/script/json2.js"></script>
<script type="text/javascript">
function autoComplete(val) {
var xmlHttp = null;
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("您的浏览器不支持AJAX");
return;
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
clearTip();
    setPosition();
var words = eval('(' + xmlHttp.responseText + ')');
if(words.length > 0){
var tip = document.getElementById("tip");
    var word = document.getElementById("word");
    var tb = document.getElementById("tb");
   
    for (var i = 0; i < words.length; i++) {
    var row = document.createElement("tr");
        var cell = document.createElement("td");
    cell.style.width = (word.offsetWidth - 2) + "px";
        cell.style.padding = "2px";
        cell.onmouseout = function() {this.className='mouseOut';};
        cell.onmouseover = function() {this.className='mouseOver';};
        cell.onclick = function() {word.value = this.firstChild.nodeValue;clearTip();};
        var content = document.createTextNode(words[i]);
        cell.appendChild(content);
        row.appendChild(cell);
        tb.appendChild(row);
    }
    tip.style.border = "#000000 1px solid";
}
}
};
xmlHttp.open("GET", "${basePath}/AutoCompleteServlet?word=" + val + "&time=" + new Date().getTime());
xmlHttp.send(null);
}

function setPosition() {
    var word = document.getElementById("word");
    var top = getOffsetTOP(word);
    var left = getOffsetLeft(word);
    var tip = document.getElementById("tip");
    tip.style.top = top + word.offsetHeight + "px";
    tip.style.left = left + "px";
}

function getOffsetTOP(elem) {
    var top = 0;
    while (elem) {
        top += elem.offsetTop;
        elem = elem.offsetParent;
    }
    return top;
}

function getOffsetLeft(elem) {
    var left = 0;
    while (elem) {
        left += elem.offsetLeft;
        elem = elem.offsetParent;
    }
    return left;
}

function clearTip() {
var tip = document.getElementById("tip");
    tip.style.border = "none";
    var tb = document.getElementById("tb");
    while (tb.hasChildNodes()) {
        tb.removeChild(tb.firstChild);
    }
}

</script>
</head>
<body>
<h1>
AutoComplete
</h1>
<br />
<input id="word" type="text" onkeyup="autoComplete(this.value)"/>
<div id="tip">
<table id="tab" cellpadding="0" cellspacing="0">
<tbody id="tb"></tbody>
</table>
</div>
</body>
</html>

public class AutoCompleteServlet extends HttpServlet {
List<String> words = new ArrayList<String>();

@Override
public void init() throws ServletException {
super.init();
words.add("J2SE");
words.add("J2ME");
words.add("J2EE");
words.add("Java");
words.add("JSP");
words.add("Servlet");
words.add("Oracle");
words.add("Tomcat");
words.add("AAAAAAA");
words.add("BBBBBBB");
words.add("CCCCCCC");
words.add("DDDDDDD");
words.add("EEEEEEE");
words.add("FFFFFFF");
words.add("GGGGGGG");
}

private List<String> search(String word) {
List<String> results = new ArrayList<String>();
for (String str : words) {
if (str.toUpperCase().startsWith(word.toUpperCase())) {
results.add(str);
}
}
return results;
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
String word = request.getParameter("word").trim();
String back_val = "";

if (word != null && word.length() > 0) {
back_val = JSONArray.fromObject(search(word)).toString();
System.out.println(back_val);
}

PrintWriter out = response.getWriter();
out.print(back_val);
out.flush();
out.close();
}
}

你可能感兴趣的:(oracle,jsp,json,Ajax,servlet)