在這個例子中,首先出現的html表單用來選擇搜索引擎、搜索字符串、每頁顯示的搜索結果數量。表單提交后,servlet提取這三個變量,按照所選擇的搜索引擎的要求構造出包含這些變量的url,然后把用戶重定向到這個url。如果用戶不能正確地選擇搜索引擎,或者利用其他表單發送了一個不認識的搜索引擎名字,則返回一個提示搜索引擎找不到的404頁面。
searchengines.java
注意:這個servlet要用到后面給出的searchspec類,searchspec的功能是構造適合不同搜索引擎的url。
package hall;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
public class searchengines extends httpservlet {
public void doget(httpservletrequest request,
httpservletresponse response)
throws servletexception, ioexception {
// getparameter自動解碼url編碼的查詢字符串。由于我們
// 要把查詢字符串發送給另一個服務器,因此再次使用
// urlencoder進行url編碼
string searchstring =
urlencoder.encode(request.getparameter("searchstring"));
string numresults =
request.getparameter("numresults");
string searchengine =
request.getparameter("searchengine");
searchspec[] commonspecs = searchspec.getcommonspecs();
for(int i=0; i<commonspecs.length; i++) {
searchspec searchspec = commonspecs[i];
if (searchspec.getname().equals(searchengine)) {
string url =
response.encodeurl(searchspec.makeurl(searchstring,
numresults));
response.sendredirect(url);
return;
}
}
response.senderror(response.sc_not_found,
"no recognized search engine specified.");
}
public void dopost(httpservletrequest request,
httpservletresponse response)
throws servletexception, ioexception {
doget(request, response);
}
}
searchspec.java
package hall;
class searchspec {
private string name, baseurl, numresultssuffix;
private static searchspec[] commonspecs =
{ new searchspec("google",
"http://www.google.com/search?q=",
"&num="),
new searchspec("infoseek",
"http://infoseek.go.com/titles?qt=",
"&nh="),
new searchspec("lycos",
"http://lycospro.lycos.com/cgi-bin/pursuit?query=",
"&maxhits="),
new searchspec("hotbot",
"http://www.hotbot.com/?mt=",
"&dc=")
};
public searchspec(string name,
string baseurl,
string numresultssuffix) {
this.name = name;
this.baseurl = baseurl;
this.numresultssuffix = numresultssuffix;
}
public string makeurl(string searchstring, string numresults) {
return(baseurl + searchstring + numresultssuffix + numresults);
}
public string getname() {
return(name);
}
public static searchspec[] getcommonspecs() {
return(commonspecs);
}
}
searchengines.html
下面是調用上述servlet的html表單。
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title>訪問多個搜索引擎</title>
</head>
<body bgcolor="#fdf5e6">
<form action="/servlet/hall.searchengines">
<center>
搜索關鍵字:
<input type="text" name="searchstring"><br>
每頁顯示幾個查詢結果:
<input type="text" name="numresults"
value=10 size=3><br>
<input type="radio" name="searchengine"
value="google">
google |
<input type="radio" name="searchengine"
value="infoseek">
infoseek |
<input type="radio" name="searchengine"
value="lycos">
lycos |
<input type="radio" name="searchengine"
value="hotbot">
hotbot
<br>
<input type="submit" value="search">
</center>
</form>
</body>
</html>
新聞熱點
疑難解答