关于Servlet开发的流程推荐看servlet开发-通过Tomcat部署一个简单的webapp
Servlet开发与idea集成的插件安装推荐看idea集成tomcat(Smart Tomcate插件安装)
postman(第三方创建HTTP请求工具)的安装推荐看创建HTTP请求的几种方式
HttpServletRequest类是Servlet开发常用的类之一
HttpServletRequest类的方法:

- 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.IOException;
- import java.util.Enumeration;
-
- /**
- * Created with IntelliJ IDEA.
- * Description:
- * User: wuyulin
- * Date: 2023-09-22
- * Time: 12:19
- */
- //通过HttpServletRequest中的方法去获取并打印HTTP请求的信息
- @WebServlet("/request")
- public class HttpServletRequestExercise extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //由于要通过br来对返回给用户的数据换行,所以http响应数据报的类型应该是html类型,要显式设置一下
- resp.setContentType("text/html");
-
- //用StringBuilder对象来拼接Http请求的内容
- StringBuilder http_rep=new StringBuilder();
-
- //Http请求的请求头部分
- //拼接Http请求的方法
- http_rep.append(req.getMethod()+" ");
- //拼接Http请求的URI
- http_rep.append(req.getRequestURI());
- //拼接Http请求的URI的ContextPath部分
- http_rep.append(req.getContextPath());
- //拼接Http请求的URL中的查询字符串
- http_rep.append("?"+req.getQueryString());
- //拼接Http请求的版本号
- http_rep.append(req.getProtocol()+"
"); -
- //Http请求的Header部分
- //Header中就是一些键值对,大多数是统一规定的,少部分是程序员自己定义的
- //先获取到Header中所有的key值,放到一个枚举中
- Enumeration
header_key= req.getHeaderNames(); - //遍历枚举中的key值
- //判断枚举中是否还有元素,有的话就取出来,没有的话就停止循环
- while (header_key.hasMoreElements()){
- String key=header_key.nextElement();
- http_rep.append(key+"="+req.getHeader(key)+"
"); - }
-
- //把http_rep字符串中的数据传到resp响应对象中(传到了http响应报文的body中)
- resp.getWriter().write(http_rep.toString());
- }
- }
写好代码部署好webapp后,我们便可以通过postman工具向部署好的webapp发起一个请求,就能得到如下的效果

我们可以看到,通过HttpServletRequest类中的方法得到了HTTP请求的信息