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将会读取所有请求头的名称和值,并将其输出到页面上。