image.png

    1. package com.itheima.web;
    2. import javax.servlet.ServletException;
    3. import javax.servlet.annotation.WebServlet;
    4. import javax.servlet.http.HttpServlet;
    5. import javax.servlet.http.HttpServletRequest;
    6. import javax.servlet.http.HttpServletResponse;
    7. import java.io.BufferedReader;
    8. import java.io.IOException;
    9. /**
    10. * request 获取请求数据
    11. */
    12. @WebServlet("/req1")
    13. public class RequestDemo1 extends HttpServlet {
    14. @Override
    15. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    16. // String getMethod():获取请求方式: GET
    17. String method = req.getMethod();
    18. System.out.println(method);//GET
    19. // String getContextPath():获取虚拟目录(项目访问路径):/request-demo
    20. String contextPath = req.getContextPath();
    21. System.out.println(contextPath);
    22. // StringBuffer getRequestURL(): 获取URL(统一资源定位符):http://localhost:8080/request-demo/req1
    23. StringBuffer url = req.getRequestURL();
    24. System.out.println(url.toString());
    25. // String getRequestURI():获取URI(统一资源标识符): /request-demo/req1
    26. String uri = req.getRequestURI();
    27. System.out.println(uri);
    28. // String getQueryString():获取请求参数(GET方式): username=zhangsan
    29. String queryString = req.getQueryString();
    30. System.out.println(queryString);
    31. //
    32. //
    33. //------------
    34. // 获取请求头:user-agent: 浏览器的版本信息
    35. String agent = req.getHeader("user-agent");
    36. System.out.println(agent);
    37. }
    38. @Override
    39. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    40. //获取post 请求体:请求参数
    41. //1. 获取字符输入流
    42. BufferedReader br = req.getReader();
    43. //2. 读取数据
    44. String line = br.readLine();
    45. System.out.println(line);
    46. }
    47. }

    定义使用post方法提交表单

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Title</title>
    6. </head>
    7. <body>
    8. <!-- 定义一个表单,使用post提交 表单访问路径写 项目下的 req1(也就是RequsetDemo1.java文件-->
    9. <form action="/request-demo/req1" method="post">
    10. <input type="text" name="username">
    11. <input type="password" name="password">
    12. <input type="submit">
    13. </form>
    14. </body>
    15. </html>