请求行:GET/request-demo/req1?/username=zhangsan HTTP/1.1
1.请求行:
*String getMethod():获取请求方式 GET
*String getContextPath():获取虚拟目录(项目访问路径):/request-demo
*StringBuffer getRequestURL():获取url(统一资源定位符):http:/localhost:8080/request-demo/req1
*String getRequestURL():获取url(统一资源定位符):/request-demo/req1
*String getQueryString():获取请求参数(GET)/username=zhangsan&password=123
2.请求头 :
例如:User-Agent:Mozilla/5.0 Chrome/103.0.5060.134//获取客户端浏览器的版本信息
String getHeader(String name):根据请求头名称,获取值
3.请求体:
例如:username=zhangsan&password=123
ServletInputStream getInputStream():获取字节输入流
BufferReader getReader():获取字符输入流
代码演示:
- package com.itheima.web;
-
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.BufferedReader;
- import java.io.IOException;
-
- @WebServlet("/req1")
- public class request_demo01 extends HttpServlet {
- /*
- *String getMethod():获取请求方式 GET
- *String getContextPath():获取虚拟目录(项目访问路径):/request-demo
- *StringBuffer getRequestURL():获取url(统一资源定位符):http:/localhost:8080/request-demo/req1
- *String getRequestURL():获取url(统一资源定位符):/request-demo/req1
- *String getQueryString():获取请求参数(GET)/username=zhangsan&password=123
- */
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- String method = req.getMethod();
- System.out.println(method); //获取请求方式 GET
-
- String contextPath = req.getContextPath();
- System.out.println(contextPath);//获取虚拟目录(项目访问路径)(模块)
-
- StringBuffer stringBufferRequestURL = req.getRequestURL();
- System.out.println(stringBufferRequestURL);//获取url(统一资源定位符),获取全目录
-
- String requestURI = req.getRequestURI();
- System.out.println(requestURI);//获取url(统一资源定位符)(模块+访问文件名称)
-
- String queryString = req.getQueryString();
- System.out.println(queryString);//:获取请求参数(GET)地址栏参数
-
-
- //-------------
- //获取请求头浏览器版信息
- String header = req.getHeader("User-Agent");
- System.out.println(header);
-
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //-------------
- //获取请求体POST
- //1.获取字符输入流
- BufferedReader reader = req.getReader();
- //读取数据
- String s = reader.readLine();
- System.out.println(s);
- }
- }
总结:
1.第一行是获取post的请求体
2.最后一行是获取请求头,也就是浏览器的版本
3.中间的几行是获取的去请求行,也就是地址栏里面的参数