js
在這個例子中,首先出現的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>