在这个例子中,首先出现的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>
新闻热点
疑难解答