2.1 HttpServletRequest類
您的 servlet 必鬚根據從請求中收到的信息來完成大部分工作。該對象負責它HttpServletRequest
,容器將傳遞給您的 servlet(傳遞給一個service
或多個方法doGet()
等doPost()
)
這個對像有很多方法,因為它只是存儲請求數據,你可以通過它與容器進行交互。
方法可分為兩大類:
- 用戶授權相關方法
- 處理請求數據的方法
用戶授權方式我會以表格的形式給出,我們就不分析了。事實上,它們很少用於授權用戶。所有流行的框架都使用自己的、更高級的授權方法。
我應該列出它們,但同樣,我還沒有看到有人使用它們。
方法 | 描述 | |
---|---|---|
1個 | authenticate(HttpServletResponse) |
執行響應認證 |
2個 | changeSessionId() |
強制更改會話 ID |
3個 | getAuthType() |
返回使用的身份驗證類型:ASIC_AUTH、FORM_AUTH、CLIENT_CERT_AUTH、DIGEST_AUTH |
4個 | getRemoteUser() |
返回用戶登錄 |
5個 | getRequestedSessionId() |
返回客戶端的 SessionID |
6個 | getSession() |
返回一個 HttpSession 對象 |
7 | getUserPrincipal() |
返回一個 java.security.Principal 對象 |
8個 | login(username, password) |
執行用戶登錄 |
9 | logout() |
註銷用戶會話 |
2.2 請求數據
第二組方法更有趣。我們在請求中有什麼樣的數據?
- http方法
- 網址
- 選項
- 標題
讓我們看看有哪些方法可用於處理它們:
方法 | 描述 | |
---|---|---|
1個 | getMethod() |
返回 HTTP 方法:GET、POST、DELETE、... |
2個 | getRequestURI() |
返回請求 URI: http: //codegym.cc/my/data |
3個 | getRequestURL() |
返回請求 URL: http: //codegym.cc/my/data |
4個 | getQueryString() |
返回查詢,即 ? 之後的所有內容 |
5個 | getParameterMap() |
返回查詢參數列表 |
6個 | getParameter(String name) |
通過名稱返回參數的值 |
7 | getContentType() |
返回 MimeType 請求正文 |
8個 | getReader() |
閱讀器以文本形式閱讀請求正文 |
9 | getInputStream() |
InputStream 將請求體讀取為 byte[] |
10 | getSession() |
返回一個 HttpSession 對象 |
十一 | getCookies() |
返回一個 Cookie[] 對像數組 |
12 | getHeaderNames() |
返回標題列表,僅名稱 |
13 | getHeader(String name) |
按名稱返回標頭值 |
14 | getServletPath() |
返回引用 servlet 的 URL 部分 |
15 | getContextPath() |
返回指定請求內容的 URI 部分 |
這甚至不是所有的方法......
雖然在我們研究了 HTTP 協議並學習瞭如何使用 HttpClient 之後,這裡的一切都或多或少是熟悉的,不是嗎?
讓我們編寫一個可以向其傳遞文本和顏色的 servlet,它將返回一個 HTML 頁面,其中包含以指定顏色書寫的文本。你覺得這個主意怎麼樣?
讓我們從編寫我們的 servlet 開始:
public class ColorTextServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
//write your code here
}
}
現在我們需要獲取用戶從 URI 傳遞的文本和顏色:
public class ColorTextServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
// Getting the parameter “text” and “color” from request
String text= request.getParameter("text");
String color = request.getParameter("color");
}
}
最後,您需要將文本輸出為 HTML。我們將在下一講中介紹這一點,但在這裡我會給出一點提示:
public class ColorTextServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
// Get the "text" and "color" parameters from the request
String text = request.getParameter("text");
String color = request.getParameter("color");
// Print the HTML as a response to the browser
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head> <title> ColorTextServlet </title> </head>");
out.println("<body>");
out.println("<h1 style="color:"+color+">"+text+"</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}
GO TO FULL VERSION