`
onehao
  • 浏览: 13406 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

Servlet与JSP核心编程 ---- 5

阅读更多

5.5Differentiating Among Different Browser Types

 

Use User-Agent only when necessary

 

Check for null

 

To differentiate between Netscape and Internet Explorer, check for “MSIE,” not “Mozilla.”

 

Note that the header can be faked.

 

package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Servlet that gives browser-specific insult.
* Illustrates how to use the User-Agent
* header to tell browsers apart.
*/
public class BrowserInsult extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title, message;
// Assume for simplicity that Netscape and IE are
// the only two browsers.
String userAgent = request.getHeader("User-Agent");
if ((userAgent != null) &&
(userAgent.indexOf("MSIE") != -1)) {
title = "Microsoft Minion";
message = "Welcome, O spineless slave to the " +
"mighty empire.";
} else {
title = "Hopeless Netscape Rebel";
message = "Enjoy it while you can. " +
"You <I>will</I> be assimilated!";
}
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
message + "\n" +
"</BODY></HTML>");
}
}

 

 

5.6Changing the Page According to How the User Got There

 

package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Servlet that displays referer-specific image. */
public class CustomizeImage extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String referer = request.getHeader("Referer");
if (referer == null) {
referer = "<I>none</I>";
}
String title = "Referring page: " + referer;
String imageName;
if (contains(referer, "JRun")) {
imageName = "jrun-powered.gif";
} else if (contains(referer, "Resin")) {
imageName = "resin-powered.gif";
} else {
imageName = "tomcat-powered.gif";
}
String imagePath = "../request-headers/images/" + imageName;
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<CENTER><H2>" + title + "</H2>\n" +
"<IMG SRC=\"" + imagePath + "\">\n" +
"</CENTER></BODY></HTML>");
}
private boolean contains(String mainString,
String subString) {
return(mainString.indexOf(subString) != -1);
}
}

 

 

 

5.7 Accessing the Standard CGI Variables

 

A Servlet That Shows the CGI Variables

 

package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
/** Creates a table showing the current value of each
* of the standard CGI variables.
*/
public class ShowCGIVariables extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String[][] variables =
{ { "AUTH_TYPE", request.getAuthType() },
{ "CONTENT_LENGTH",
String.valueOf(request.getContentLength()) },
{ "CONTENT_TYPE", request.getContentType() },
{ "DOCUMENT_ROOT",
getServletContext().getRealPath("/") },
{ "PATH_INFO", request.getPathInfo() },
{ "PATH_TRANSLATED", request.getPathTranslated() },
{ "QUERY_STRING", request.getQueryString() },
{ "REMOTE_ADDR", request.getRemoteAddr() },
{ "REMOTE_HOST", request.getRemoteHost() },
{ "REMOTE_USER", request.getRemoteUser() },
{ "REQUEST_METHOD", request.getMethod() },
{ "SCRIPT_NAME", request.getServletPath() },
{ "SERVER_NAME", request.getServerName() },
{ "SERVER_PORT",
String.valueOf(request.getServerPort()) },
{ "SERVER_PROTOCOL", request.getProtocol() },
{ "SERVER_SOFTWARE",
getServletContext().getServerInfo() }
};
String title = "Servlet Example: Showing CGI Variables";
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<CENTER>\n" +
"<H1>" + title + "</H1>\n" +
"<TABLE BORDER=1>\n" +
" <TR BGCOLOR=\"#FFAD00\">\n" +
" <TH>CGI Variable Name<TH>Value");
for(int i=0; i<variables.length; i++) {
String varName = variables[i][0];
String varValue = variables[i][1];
if (varValue == null)
varValue = "<I>Not specified</I>";
out.println(" <TR><TD>" + varName + "<TD>" + varValue);
}
out.println("</TABLE></CENTER></BODY></HTML>");
}
/** POST and GET requests handled identically. */
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

 

 

6.2 HTTP 1.1 Status Codes

100–199

Codes in the 100s are informational, indicating that the client should

respond with some other action.

• 200–299

Values in the 200s signify that the request was successful.

• 300–399

Values in the 300s are used for files that have moved and usually

include a Location header indicating the new address.

• 400–499

Values in the 400s indicate an error by the client.

• 500–599

Codes in the 500s signify an error by the server.

 

6.4A Front End to Various Search Engines

 

package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
/** Servlet that takes a search string and a search
* engine name, sending the query to
* that search engine. Illustrates manipulating
* the response status code. It sends a 302 response
* (via sendRedirect) if it gets a known search engine,
* and sends a 404 response (via sendError) otherwise.
*/
public class SearchEngines extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String searchString = request.getParameter("searchString");
if ((searchString == null) ||
(searchString.length() == 0)) {
reportProblem(response, "Missing search string");
return;
}
// The URLEncoder changes spaces to "+" signs and other
// non-alphanumeric characters to "%XY", where XY is the
// hex value of the ASCII (or ISO Latin-1) character.
// Browsers always URL-encode form values, and the
// getParameter method decodes automatically. But since
// we're just passing this on to another server, we need to
// re-encode it to avoid characters that are illegal in
// URLs. Also note that JDK 1.4 introduced a two-argument
// version of URLEncoder.encode and deprecated the one-arg
// version. However, since version 2.3 of the servlet spec
// mandates only the Java 2 Platform (JDK 1.2 or later),
// we stick with the one-arg version for portability.
searchString = URLEncoder.encode(searchString);
String searchEngineName =
request.getParameter("searchEngine");
if ((searchEngineName == null) ||
(searchEngineName.length() == 0)) {
reportProblem(response, "Missing search engine name");
return;
}
String searchURL =
SearchUtilities.makeURL(searchEngineName, searchString);
if (searchURL != null) {
response.sendRedirect(searchURL);
} else {
reportProblem(response, "Unrecognized search engine");
}
}
private void reportProblem(HttpServletResponse response,
String message)
throws IOException {
response.sendError(response.SC_NOT_FOUND, message);
}
}

 

 

 

package coreservlets;
/** Small class that encapsulates how to construct a
* search string for a particular search engine.
*/
public class SearchSpec {
private String name, baseURL;
public SearchSpec(String name,
String baseURL) {
this.name = name;
this.baseURL = baseURL;
}
/** Builds a URL for the results page by simply concatenating
* the base URL (http://...?someVar=") with the URL-encoded
* search string (jsp+training).
*/
public String makeURL(String searchString) {
return(baseURL + searchString);
}
public String getName() {
return(name);
}
}

 

 

 

 

package coreservlets;
/** Utility with static method to build a URL for any
* of the most popular search engines.
*/
public class SearchUtilities {
private static SearchSpec[] commonSpecs =
{ new SearchSpec("Google",
"http://www.google.com/search?q="),
new SearchSpec("AllTheWeb",
"http://www.alltheweb.com/search?q="),new SearchSpec("Yahoo",
"http://search.yahoo.com/bin/search?p="),
new SearchSpec("AltaVista",
"http://www.altavista.com/web/results?q="),
new SearchSpec("Lycos",
"search.lycos.com/default.asp?query="),
new SearchSpec("HotBot",
"http://hotbot.com/default.asp?query="),
new SearchSpec("MSN",
"http://search.msn.com/results.asp?q="),
};
public static SearchSpec[] getCommonSpecs() {
return(commonSpecs);
}
/** Given a search engine name and a search string, builds
* a URL for the results page of that search engine
* for that query. Returns null if the search engine name
* is not one of the ones it knows about.
*/
public static String makeURL(String searchEngineName,
String searchString) {
SearchSpec[] searchSpecs = getCommonSpecs();
String searchURL = null;
for(int i=0; i<searchSpecs.length; i++) {
SearchSpec spec = searchSpecs[i];
if (spec.getName().equalsIgnoreCase(searchEngineName)) {
searchURL = spec.makeURL(searchString);
break;
}
}
return(searchURL);
}
}
 
分享到:
评论

相关推荐

    Servlet与JSP核心编程(第二版).pdf

    Servlet与JSP核心编程:综合介绍Servlet与JSP

    Servlet与JSP核心编程(第二版)

    《Servlet与JSP核心编程(第二版)》是一本针对Java Web开发的权威指南,主要聚焦于Servlet和JSP这两个核心技术。Servlet是Java平台上的服务器端组件,用于处理HTTP请求,而JSP(JavaServer Pages)则是一种动态网页...

    Servlet与JSP核心编程

    《Servlet与JSP核心编程(第2卷 第2版)》在第l卷的基础上,广泛涉及自定义标签库、过滤器、声明式安全、JSTL和Struts等主题,并沿袭深受读者喜爱的写作风格,通过完整、有效、资料丰富的程序来演绎目前最流行的技术和...

    Servlet与JSP核心编程(第2卷 第2版)

    《Servlet与JSP核心编程(第2卷 第2版)》这本书深入讲解了这两项技术,帮助开发者理解并掌握其核心概念、用法以及最佳实践。 1. **Servlet概述** - Servlet是Java平台上的一个接口,它定义了服务器端程序如何响应...

    Servlet与JSP核心编程第二版

    Servlet与JSP核心编程第二版 PDF文件 高清,内容通俗易懂.

    Servlet与JSP核心编程第二版5

    ### Servlet与JSP核心编程第二版5:关键技术与实践解析 #### 一、Servlet概述与核心技术 ##### 1.1 Servlet简介 Servlet 是 Java 平台的一种服务器端技术,用于扩展应用程序的功能。它是一个轻量级的应用程序组件...

    Servlet与JSP核心编程第二版源代码

    《Servlet与JSP核心编程第二版》这本书深入浅出地讲解了这两个技术,涵盖了从基础到高级的主题,包括但不限于: 1. **Servlet生命周期**:Servlet的创建、初始化、服务和销毁过程,以及如何通过配置`web.xml`文件或...

    servlet与jsp核心编程

    servlet与jsp核心编程,还是免费给大家下载,需要的可以下来看看

    Servlet与JSP核心编程带完整书签

    《Servlet与JSP核心编程》由浅入深,全面而深入地介绍了servlet和jsp技术。本书重点介绍核心技术,同时对相关的内容,如web服务器的配置、安装和应用,数据库的安装和配置等都做了详细明了的介绍。本书的例子简练...

    Servlet与JSP核心编程第二版(含书签)

    ### Servlet与JSP核心编程知识点概述 #### 一、Servlet基础概念 - **Servlet定义**:Servlet是一种Java程序,用于扩展服务器的功能。它提供了一种方法来创建动态Web页面,并可以处理客户端请求。 - **Servlet生命...

    javax.servlet.jsp-api-2.3.2-b01.jar.zip

    Servlet API是Java Web开发的核心组件,它定义了服务器端Java应用程序(Servlet)与Web服务器之间的接口规范。Servlet API提供了处理HTTP请求和响应的方法,允许开发人员创建能够接收和处理来自客户端(如浏览器)的...

    servlet 与jsp核心编程 第二版中文版 第3部分

    本书由Marty Hall,Larry Brown著 张学良译 清华大学出版社出版 原书有47M由于上传文件大小限制分为3部分,本人不是黑人,仅仅在最后一个部分才收取4分资源分

    Servlet与JSP核心编程(第二版 源码

    《Servlet与JSP核心编程》由浅入深,全面而深入地介绍了servlet和jsp技术。本书重点介绍核心技术,同时对相关的内容,如web服务器的配置、安装和应用,数据库的安装和配置等都做了详细明了的介绍。本书的例子简练...

    javax.servlet---jsp-api jar包

    5. **版本升级与兼容性**: 随着Java EE版本的升级,Servlet和JSP API也有相应的更新,如Servlet 2.x, 3.x, 4.x等,每个新版本通常会引入新的特性和性能优化,并保持向后兼容。开发者需要根据项目需求选择合适的API...

    servlet与jsp核心编程*(第二版)卷二 源代码集合

    本书《Servlet与JSP核心编程(第二版)卷二》的源代码集合,为读者提供了丰富的实践素材,有助于深入理解这两种技术的内部工作原理。 Servlet是一种Java API,用于扩展服务器的功能,处理HTTP请求并生成响应。它...

    《Servlet与JSP核心编程(第1卷 第2版)》

    综上所述,《Servlet与JSP核心编程(第1卷 第2版)》这本书很可能是深入探讨了Servlet与JSP的基础理论、核心技术及其实战应用的一本书籍。对于想要学习或深入理解这些技术的人来说,这本书将是非常有价值的资源。

    Servlet与JSP核心编程 第1卷 + 第2卷

    《Servlet与JSP核心编程》(第2版)叙述详尽,条理清晰。对于初学者来说是一本不可多得的入门书籍,经验丰富的Servelet和JSP开发人员也可以通过阅读《Servlet与JSP核心编程》(第2版)得到巩固和提高。

    美河图书提供.Servlet与JSP核心编程第二版_带目录

    ### Servlet与JSP核心编程第二版知识点概览 #### 一、Servlet基础知识 - **Servlet概念**:Servlet是一种运行在服务器端的小程序,主要用于处理客户端请求并生成动态Web页面或数据。Servlet是Java Web开发的基础...

Global site tag (gtag.js) - Google Analytics