一、HttpServletRequest类
HttpServletRequest 类作用
每次只要有请求进入Tomcat服务器,Tomcat服务器就会把请求过来的HTTP协议信息解析好封装到 Request 对象中。然后传递到 service方法(doGet 和 doPost)中给我们使用。我们可以通过 HttpServletRequest 对象,获取到所有请求的信息.
1.1 HttpServletRequest类的常用方法
常用方法 | 方法介绍 |
---|---|
String getParameter(String name) | 返回name指定参数的参数值 |
String[] getParameterValues(String name) | 返回包含参数name的所有值的数组 |
void setAttribute(String,Object) | 存储此请求中的属性 |
Object getAttribute(String name) | 返回指定属性的属性值 |
String getContentType() | 得到请求体的MIME类型 |
String getProtocol() | 返回请求用的协议类型及版本号 |
String getServerName() | 返回接受请求的服务器主机名 |
int getServerPort() | 返回服务器接受此请求所用的端口号 |
String getCharacterEncoding() | 返回字符编码方式 |
void setCharacterEncoding() | 设置请求的字符编码方式 |
int getContentLength() | 返回请求体的长度(以字节数) |
String getRemoteAddr() | 返回发送此请求的客户端IP地址 |
String getRealPath(String path) | 返回一虚拟路径的真实路径 |
String request.getContextPath() | 获取当前工程路径 |
getRequestDispatcher() | 获取请求转发对象 |
getRequestURI() | 获取请求的资源路径 |
getRequestURL() | 获取请求的统一资源定位符(绝对路径) |
getHeader(String name) | 得HTTP协议定义的文件头信息 |
getMethod() | 获取请求的方式 GET 或 POST |
-
常用方法实例
public class RequestAPIServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws javax.servlet.ServletException, IOException { // getRequestURI() 获取请求的资源路径 System.out.println("URI="+req.getRequestURI());//"/07_servlet/RequestAPIServlet" // getRequestURL() 获取请求的统一资源定位符(绝对路径) System.out.println("URL="+req.getRequestURL());//"http://localhost:8080/07_servlet/RequestAPIServlet" // getRemoteHost() 获取客户端的ip地址 /** * 在IDEA中,使用localhost访问时,得到的客户端 ip 地址是 ===>>> 127.0.0.1<br/> * 在IDEA中,使用127.0.0.1访问时,得到的客户端 ip 地址是 ===>>> 127.0.0.1<br/> * 在IDEA中,使用 真实ip 访问时,得到的客户端 ip 地址是 ===>>> 真实的客户端 ip 地址<br/> */ System.out.println("客户端ip地址:"+req.getRemoteHost()); // iv.getHeader() 获取请求头 System.out.println("请求头User-Agent ==>> "+req.getHeader("User-Agent")); // vii.getMethod() 获取请求的方式GET或POST System.out.println("请求的方式 ==>> " + req.getMethod()); //getContextPath()返回获取当前工程路径 System.out.println("获取当前工程路径:"+req.getContextPath());// “/07_servlet” } }
-
获取请求参数
@Override protected void doGet(