答案:
客户端的javascript:
<script language="javascript">
var theURL = "/examples/servlet/MyGoogleSearchServlet?search=";
var http = getHTTPObject();
function handleHttpResponse() {
if (http.readyState == 4) {
GoogleSearchResults.innerHTML = http.responseText;
}
}
function updateGoogleResults(formElement) {
var searchQuery = document.forms[0].elements[formElement].value;
http.open("GET", theURL + escape(searchQuery), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function getHTTPObject() {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != ’undefined’) {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
</script>
__________________________________________________________________________
服务器端的:MyGoogleSearchServlet
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Search Google.
*
* @author Jose Sandoval
*/
public class MyGoogleSearchServlet extends HttpServlet {
/**
* Do get.
*
* @param request HttpServletRequest
* @param response HttpServletResponse
* @throws ServletException, IOExeption
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
StringBuffer resultBuffer = new StringBuffer();
ArrayList results = MyGoogleSearch.doSearch(request.getParameter("search"));
SearchResultBean resultBean = null;
for (int i = 0; i<results.size(); i++) {
resultBean = (SearchResultBean) results.get(i);
resultBuffer.append("<a href=> resultBuffer.append("<br>");
resultBuffer.append(resultBean.getSnippet());
resultBuffer.append("<br>").append("<br>");
}
response.setContentType("text/html");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "no-store");
out.print(resultBuffer.toString());
out.close();
}
}
__________________________________________________________________________
服务器端的:MyGoogleSearch
import java.io.IOException;
import java.util.ArrayList;
import com.google.soap.search.GoogleSearch;
import com.google.soap.search.GoogleSearchFault;
import com.google.soap.search.GoogleSearchResult;
import com.google.soap.search.GoogleSearchResultElement;
/**
* GoogleSearch.
*
* @author Jose Sandoval
*/
public class MyGoogleSearch {
private static String CLIENT_KEY = "YOU_HAVE_TO_GET_YOUR_OWN_KEY_FROM_GOOGLE";
/**
* Search Google.
*
* @param queryString String
* @return ArrayList Contains SimpleSearchResult
* @throws IOException
*/
public static ArrayList doSearch(String queryString) throws IOException {
ArrayList 
上一个:JSP用中收集数据:javascript 实现输入多行动态输入
下一个:Java和javac这两个SUN公司的路盲