Servlet可以通過HttpServletRequest對象來讀取請求頭。HttpServletRequest對象提供了多個方法來獲取請求頭的信息,以下是一些常用的方法:
示例代碼如下:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.Enumeration;
public class ReadHeaderServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Reading Request Header</title></head>");
out.println("<body>");
// 獲取所有請求頭的名稱
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
out.println(headerName + ": " + headerValue + "<br>");
}
out.println("</body>");
out.println("</html>");
}
}
當客戶端發送請求時,該Servlet將會讀取所有請求頭的名稱和值,并將其輸出到頁面上。