當HTTP轉發給Web容器處理時,Web容器會收集相關信息,並產生HttpServletRequest對象,使用這個對象可以取得所有HTTP請求中的信息,可以在Servlet中進行處理,也可以轉發給其他的Servlet/Jsp處理。
1. 請求信息的取得
getQueryString()方法可以取得HTTP請求的查詢字符串。
getParameter()方法能指定請求參數名稱來取得相應的值,如取得下面請求參數為name 的值:
http://localhost:8080/WebApp1/hello.do?name=acmagic;
獲取到的name 的值就為acmagic,如果請求中沒有參數的名稱,則返回null.
如果窗口上一個參數名稱有多個值,此時可以用getParameterValues()方法取得一個String數組。例如:
http://localhost:8080/WebApp1/hello.do?choose=sans&choose=lily&choose=jack
String[] names = request.getParameterValues("choose");
如果要知道有多少請求參數,可以使用getParameterNames()方法,他會返回一個Enumeration對象,其中包括所有請求參數的名稱。例如:
Enumeration<String> e = request.getParameterNames();
while (e.hasMoreElements()) {
String param = (String) e.nextElement();
out.println(param + "<br>");
}
如果要知道瀏覽器請求的標頭,可以用getHeader()方法,也可以使用getHeaderNames()獲取瀏覽器請求的所有標頭值。
完整代碼:
package com.web.http;
import java.awt.print.Printable;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetRequestMessage extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected void getRequestMessage(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 傳送給瀏覽器utf-8編碼的文字
response.setContentType("text/html;charset=utf-8");
//請求字符編碼,如果有中文才不會亂碼
request.setCharacterEncoding("utf-8");
PrintWriter output = response.getWriter();
output.println("<html>");
output.println("<head>");
output.println("<title>getRequestMessage</title>");
output.println("</head>");
output.println("<body>");
// 取得應用程序的路徑
output.println("<h1>This WebApp at :" + request.getContextPath() + "</h1>");
// 取得請求字符串
output.println("<p>Request string: " + request.getQueryString() + "</p>");
// 取得參數中對應的值
output.println("<p>name = " + request.getParameter("name") + "</p>");
// 一個參數對應幾個值
String[] chooses = request.getParameterValues("choose");
output.print("<p>chooses are: " + chooses[1] + "</p>");
// 請求參數的個數
Enumeration<String> e = request.getParameterNames();
while (e.hasMoreElements()) {
String param = (String) e.nextElement();
output.println(param + ":" + request.getParameter(param) + "<br><br>");
}
// 獲取所有標頭名
Enumeration<String> h = request.getHeaderNames();
while (h.hasMoreElements()) {
String head = (String) h.nextElement();
output.println(head + ": " + request.getHeader(head) + "<br>");
}
output.println("<body>");
output.println("</html?");
output.close();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
getRequestMessage(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
getRequestMessage(request, response);
}
}</font></font>
運行結果如下:
(未完。。。)
更多相關API請訪問官方文檔:http://docs.oracle.com/javaee/6/api/