在这个例子中,首先出现的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",
"&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>