这个压缩包里的都是超级经典的java例子
源代码在线查看: getheaders.htm
Getting a Request Header in a Servlet (Java Developers Almanac Example)
The Java Developers Almanac 1.4
Order this book from Amazon.
google_ad_client = "pub-6001183370374757";
google_ad_width = 120;
google_ad_height = 600;
google_ad_format = "120x600_as";
google_ad_channel = "4777242811";
google_ad_type = "text_image";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "6666CC";
google_color_url = "6666CC";
google_color_text = "000000";
//-->
Home
>
List of Packages
>
javax.servlet
[11 examples]
>
Requests
[6 examples]
e1043. Getting a Request Header in a Servlet
This example demonstrates how to get the value of a request header
in either a GET or POST request.
// See also e1035 The Quintessential Servlet
// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doGetOrPost(req, resp);
}
// This method is called by the servlet container to process a POST request.
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doGetOrPost(req, resp);
}
// This method handles both GET and POST requests.
private void doGetOrPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
resp.setContentType("text/plain");
// Get the value of a request header; the name is case-insensitive
String name = "user-agent";
String value = req.getHeader(name);
if (value == null) {
// The request header was not present
}
// Get all request headers
Enumeration enum = req.getHeaderNames();
for (; enum.hasMoreElements(); ) {
// Get the name of the request header
name = (String)enum.nextElement();
out.println(name);
// Get a value of the request header
value = req.getHeader(name);
// If the request header can appear more than once, get all values
Enumeration valuesEnum = req.getHeaders(name);
for (; valuesEnum.hasMoreElements(); ) {
// Get a value of the request header
value = (String)valuesEnum.nextElement();
out.println(" "+value);
}
}
out.close();
}
Related Examples
e1040.
Getting a Request Parameter in a Servlet
e1041.
Preventing Concurrent Requests to a Servlet
e1042.
Getting the Requesting URL in a Servlet
e1044.
Processing a HEAD Request in a Servlet
e1045.
Getting the Client's Address in a Servlet
© 2002 Addison-Wesley.