HttpServletRequest接口提供了访问HTTP请求信息
的方法,包括请求行和请求头。下面是一些常用的HttpServletRequest方法,用于获取请求行和请求头信息。
String getMethod()
: 返回请求的HTTP方法,如GET、POST等。String getRequestURI()
: 返回请求的URI,不包括查询字符串。String getQueryString()
: 返回请求的查询字符串部分。String getHeader(String name)
: 返回指定名称的请求头的值。Enumeration<String> getHeaderNames()
: 返回所有请求头名称的Enumeration对象。
代码如下:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.Enumeration;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
// 获取请求方法
String method = request.getMethod();
out.println("Request Method: " + method + "<br>");
// 获取请求URI
String requestURI = request.getRequestURI();
out.println("Request URI: " + requestURI + "<br>");
// 获取查询字符串
String queryString = request.getQueryString();
out.println("Query String: " + queryString + "<br>");
// 获取所有请求头
Enumeration<String> headerNames = request.getHeaderNames();
out.println("<br>Request Headers:<br>");
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
out.println(headerName + ": " + headerValue + "<br>");
}
out.println("</body></html>");
}
}
HttpServletRequest接口也提供了用于获取请求中键值对参数的方法:
String getParameter(String name)
: 返回指定名称的请求参数的值。Enumeration<String> getParameterNames()
: 返回所有请求参数名称的Enumeration对象。String[] getParameterValues(String name)
: 返回指定名称的请求参数的所有值。
代码如下:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.Enumeration;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
// 获取单个参数值
String param1 = request.getParameter("param1");
out.println("Parameter 'param1' value: " + param1 + "<br>");
// 获取所有参数名
Enumeration<String> parameterNames = request.getParameterNames();
out.println("<br>All Parameters:<br>");
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
out.print(paramName + ": ");
for (String value : paramValues) {
out.print(value + " ");
}
out.println("<br>");
}
out.println("</body></html>");
}
}
标签:HttpServletRequest,参数信息,请求,request,Enumeration,String,println,out
From: https://blog.csdn.net/2401_82884096/article/details/136937881