• Servlet--Request请求对象


    1.请求对象的概述

    请求:获取资源。在BS架构中,就是客户端浏览器向服务器端发出询问

    请求对象:就是在项目当中用于发送请求的对象

    2.获取各种路径的方法

    返回值方法名说明
    StringgetContextPath()获取虚拟目录名称
    StringgetServletPath()获取Servlet映射路径
    StringgetRemoteAddr()获取访问者ip地址
    StringgetQueryString()获取请求的消息数据
    StringgetRequersURI()获取统一资源标识符
    StringBuffergetRequestURL()获取统一资源定位符
    1. package servlet;
    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.IOException;
    8. @WebServlet("/servletDemo01")
    9. public class ServletDemo01 extends HttpServlet {
    10. @Override
    11. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    12. //1.获取虚拟目录名称 getContextPath()
    13. String contextPath = req.getContextPath();
    14. System.out.println(contextPath);
    15. //2.获取Servlet映射路径 getServletPath()
    16. String servletPath = req.getServletPath();
    17. System.out.println(servletPath);
    18. //3.获取访问者ip getRemoteAddr()
    19. String ip = req.getRemoteAddr();
    20. System.out.println(ip);
    21. //4.获取请求消息的数据 getQueryString() url?后边的字符串(查询字符串)
    22. String queryString = req.getQueryString();
    23. System.out.println(queryString);
    24. //5.获取统一资源标识符 getRequestURI() /request/servletDemo01 共和国
    25. String requestURI = req.getRequestURI();
    26. System.out.println(requestURI);
    27. //6.获取统一资源定位符 getRequestURL() http://localhost:8080/request/servletDemo01 中华人民共和国
    28. StringBuffer requestURL = req.getRequestURL();
    29. System.out.println(requestURL);
    30. }
    31. @Override
    32. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    33. doGet(req,resp);
    34. }
    35. }

    3.获取请求头信息的方法

    返回值方法名说明
    StringgetHeader(String name)根据请求头名称获取一个值
    EnumerationgetHeaders(String name)根据请求头名称获取多个值
    EnumerationgetHeaderNames()获取所有请求头名称
    1. package servlet;
    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.IOException;
    8. import java.util.Enumeration;
    9. /*
    10. 获取请求头信息的相关方法
    11. */
    12. @WebServlet("/servletDemo02")
    13. public class ServletDemo02 extends HttpServlet {
    14. @Override
    15. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    16. //1.根据请求头名称获取一个值
    17. String connection = req.getHeader("connection");
    18. System.out.println(connection);
    19. System.out.println("-------------------");
    20. //2.根据请求头名称获取多个值
    21. Enumeration values = req.getHeaders("accept-encoding");
    22. while(values.hasMoreElements()) {
    23. String value = values.nextElement();
    24. System.out.println(value);
    25. }
    26. System.out.println("-------------------");
    27. //3.获取所有的请求头名称
    28. Enumeration names = req.getHeaderNames();
    29. while(names.hasMoreElements()) {
    30. String name = names.nextElement();
    31. String value = req.getHeader(name);
    32. System.out.println(name + "," + value);
    33. }
    34. }
    35. @Override
    36. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    37. doGet(req,resp);
    38. }
    39. }

    4. 获取请求参数信息的方法

    返回值方法名说明
    StringgetParameter(String name)根据名称获取数据
    String[]getParameterValues(String name)根据名称获取所有数据
    EnumerationgetParameterNames()获取所有名称
    MapgetParameterMap()获取所有参数的键值对

    在web目录下创建regist.html文件

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>注册页面title>
    6. head>
    7. <body>
    8. <form action="/request/servletDemo03" method="get" autocomplete="off">
    9. 姓名:<input type="text" name="username"> <br>
    10. 密码:<input type="password" name="password"> <br>
    11. 爱好:<input type="checkbox" name="hobby" value="study">学习
    12. <input type="checkbox" name="hobby" value="game">游戏 <br>
    13. <button type="submit">注册button>
    14. form>
    15. body>
    16. html>
    1. package servlet;
    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.IOException;
    8. import java.util.Enumeration;
    9. import java.util.Map;
    10. /*
    11. 获取请求参数信息的相关方法
    12. */
    13. @WebServlet("/servletDemo03")
    14. public class ServletDemo03 extends HttpServlet {
    15. @Override
    16. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    17. //1.根据名称获取数据 getParameter()
    18. String username = req.getParameter("username");
    19. System.out.println(username);
    20. String password = req.getParameter("password");
    21. System.out.println(password);
    22. System.out.println("--------------------");
    23. //2.根据名称获取所有数据 getParameterValues()
    24. String[] hobbies = req.getParameterValues("hobby");
    25. for(String hobby : hobbies) {
    26. System.out.println(hobby);
    27. }
    28. System.out.println("--------------------");
    29. //3.获取所有名称 getParameterNames()
    30. Enumeration names = req.getParameterNames();
    31. while(names.hasMoreElements()) {
    32. String name = names.nextElement();
    33. System.out.println(name);
    34. }
    35. System.out.println("--------------------");
    36. //4.获取所有参数的键值对 getParameterMap()
    37. Map map = req.getParameterMap();
    38. for(String key : map.keySet()) {
    39. String[] values = map.get(key);
    40. System.out.print(key + ":");
    41. for(String value : values) {
    42. System.out.print(value + " ");
    43. }
    44. System.out.println();
    45. }
    46. }
    47. @Override
    48. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    49. doGet(req,resp);
    50. }
    51. }

     

    5.获取参数手动封装对象

    三种封装方式

    1.手动封装反射

    2.反射封装方式

    3.工具类封装方式

    新建bean.Student类

    1. package bean;
    2. import java.util.Arrays;
    3. public class Student {
    4. private String username;
    5. private String password;
    6. private String[] hobby;
    7. public Student() {
    8. }
    9. public Student(String username, String password, String[] hobby) {
    10. this.username = username;
    11. this.password = password;
    12. this.hobby = hobby;
    13. }
    14. public String getUsername() {
    15. return username;
    16. }
    17. public void setUsername(String username) {
    18. this.username = username;
    19. }
    20. public String getPassword() {
    21. return password;
    22. }
    23. public void setPassword(String password) {
    24. this.password = password;
    25. }
    26. public String[] getHobby() {
    27. return hobby;
    28. }
    29. public void setHobby(String[] hobby) {
    30. this.hobby = hobby;
    31. }
    32. @Override
    33. public String toString() {
    34. return "Student{" +
    35. "username='" + username + '\'' +
    36. ", password='" + password + '\'' +
    37. ", hobby=" + Arrays.toString(hobby) +
    38. '}';
    39. }
    40. }
    1. package servlet;
    2. import bean.Student;
    3. import javax.servlet.ServletException;
    4. import javax.servlet.annotation.WebServlet;
    5. import javax.servlet.http.HttpServlet;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;
    8. import java.io.IOException;
    9. /*
    10. 封装对象--手动方式
    11. */
    12. @WebServlet("/servletDemo04")
    13. public class ServletDemo04 extends HttpServlet {
    14. @Override
    15. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    16. //1.获取所有的数据
    17. String username = req.getParameter("username");
    18. String password = req.getParameter("password");
    19. String[] hobbies = req.getParameterValues("hobby");
    20. //2.封装学生对象
    21. Student stu = new Student(username,password,hobbies);
    22. //3.输出对象
    23. System.out.println(stu);
    24. }
    25. @Override
    26. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    27. doGet(req,resp);
    28. }
    29. }

    修改regist.html

    <form action="/request/servletDemo04" method="get" autocomplete="off">

    6.获取参数反射封装对象

    1. package servlet;
    2. import bean.Student;
    3. import javax.servlet.ServletException;
    4. import javax.servlet.annotation.WebServlet;
    5. import javax.servlet.http.HttpServlet;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;
    8. import java.beans.PropertyDescriptor;
    9. import java.io.IOException;
    10. import java.lang.reflect.Method;
    11. import java.util.Map;
    12. /*
    13. 封装对象--反射方式
    14. */
    15. @WebServlet("/servletDemo05")
    16. public class ServletDemo05 extends HttpServlet {
    17. @Override
    18. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    19. //1.获取所有的数据
    20. Map map = req.getParameterMap();
    21. //2.封装学生对象
    22. Student stu = new Student();
    23. //2.1遍历集合
    24. for(String name : map.keySet()) {
    25. String[] value = map.get(name);
    26. try {
    27. //2.2获取Student对象的属性描述器
    28. //构造函数的第一个参数决定是哪个属性的描述器。第二个参数是当前属性所属对象的字节码
    29. PropertyDescriptor pd = new PropertyDescriptor(name,stu.getClass());
    30. //2.3获取对应的setXxx方法
    31. Method writeMethod = pd.getWriteMethod();
    32. //2.4执行方法
    33. if(value.length > 1) {
    34. writeMethod.invoke(stu,(Object)value);//如果是多个属性值(爱好),需要转换为object
    35. }else {
    36. writeMethod.invoke(stu,value);//通过当前属性描述器的写入方法,将value写入stu对象的这个属性身上
    37. }
    38. } catch (Exception e) {
    39. e.printStackTrace();
    40. }
    41. }
    42. //3.输出对象
    43. System.out.println(stu);
    44. }
    45. @Override
    46. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    47. doGet(req,resp);
    48. }
    49. }
    <form action="/request/servletDemo05" method="get" autocomplete="off">

    7.获取参数工具类封装对象

    导入jar包

    1. package servlet;
    2. import bean.Student;
    3. import org.apache.commons.beanutils.BeanUtils;
    4. import javax.servlet.ServletException;
    5. import javax.servlet.annotation.WebServlet;
    6. import javax.servlet.http.HttpServlet;
    7. import javax.servlet.http.HttpServletRequest;
    8. import javax.servlet.http.HttpServletResponse;
    9. import java.io.IOException;
    10. import java.util.Map;
    11. /*
    12. 封装对象--工具类方式
    13. */
    14. @WebServlet("/servletDemo06")
    15. public class ServletDemo06 extends HttpServlet {
    16. @Override
    17. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    18. //1.获取所有的数据
    19. Map map = req.getParameterMap();
    20. //2.封装学生对象
    21. Student stu = new Student();
    22. try {
    23. BeanUtils.populate(stu,map);//将map中的数据,封装到stu对象中(就这么一句话就搞定了)
    24. } catch (Exception e) {
    25. e.printStackTrace();
    26. }
    27. //3.输出对象
    28. System.out.println(stu);
    29. }
    30. @Override
    31. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    32. doGet(req,resp);
    33. }
    34. }
    <form action="/request/servletDemo06" method="get" autocomplete="off">

    8.流对象获取请求信息

    返回值方法名说明
    BufferedReadergetReader()获取字符输入流
    ServletInputStreamgetInputStream()获取字节输入流
    1. package servlet;
    2. import javax.servlet.ServletException;
    3. import javax.servlet.ServletInputStream;
    4. import javax.servlet.annotation.WebServlet;
    5. import javax.servlet.http.HttpServlet;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;
    8. import java.io.IOException;
    9. @WebServlet("/servletDemo07")
    10. public class ServletDemo07 extends HttpServlet {
    11. @Override
    12. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    13. //字符流(必须是post方式)
    14. /*BufferedReader br = req.getReader();
    15. String line;
    16. while((line = br.readLine()) != null) {
    17. System.out.println(line);
    18. }*/
    19. //br.close();//这个流是从req对象中获取的,不是自己创建的,所以不需要关闭
    20. //字节流 (应用场景,请求参数中有二进制文件(图片)时)
    21. ServletInputStream is = req.getInputStream();
    22. byte[] arr = new byte[1024];
    23. int len;
    24. while((len = is.read(arr)) != -1) {
    25. System.out.println(new String(arr,0,len));
    26. }
    27. }
    28. @Override
    29. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    30. doGet(req,resp);
    31. }
    32. }
    1. <form action="/request/servletDemo06" method="post" autocomplete="off">

    流方式获取到的中文,会进行编码,所以看到的姓名是编码后的

    解决乱码问题

    GET 方式

    没有乱码问题。在 Tomcat 8版本后已经解决

    POST 方式

    有乱码问题。可以通过 setCharacterEncoding() 方法来解决

    1. //设置编码格式
    2. req.setCharacterEncoding("UTF-8");

    9.请求域

    请求域(request域):可以在一次请求范围内进行共享数据。

    一般用于请求转发的多个资源中共享数据。

    返回值方法名说明
    void

    setAttribute(String name,Object value)

    向请求域对象中储存数据
    ObjectgetAttribute(String name)通过名称获取请求域对象中的数据
    voidremoveAttribute(String name)通过名称移除请求域对象中的数据

    请求到ServletA,实现的功能,需要用到ServletB,那这时候就可以在ServletA将请求转发到ServletB

    那ServletB中可能会用到ServletA中的数据,那这时候就涉及到数据共享了

    在这里如果使用应用域来共享数据,就有点浪费了,因为我们只是在这次请求中需要共享数据,不是整个应用

    所以就用到了请求域

    10.请求转发 

    请求转发:客户端的一次请求到达后,发现需要借助其他Servle来实现功能

    特点:

            浏览器地址栏不变

            域对象中的数据不丢失

            负责转发的 Servlet 转发前后的响应正文会丢失 (ServletA的响应正文会丢失,由ServletB响应客户端)

            由转发的目的地来响应客户端

    返回值方法名说明
    RequestDispatchergetRequestDispatcher(String name)获取请求调度对象
    voidforward(ServletRequest req,ServletResponse resp)实现转发

    1. package servlet;
    2. import javax.servlet.RequestDispatcher;
    3. import javax.servlet.ServletException;
    4. import javax.servlet.annotation.WebServlet;
    5. import javax.servlet.http.HttpServlet;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;
    8. import java.io.IOException;
    9. /*
    10. 请求转发
    11. */
    12. @WebServlet("/servletDemo09")
    13. public class ServletDemo09 extends HttpServlet {
    14. @Override
    15. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    16. //设置共享数据
    17. req.setAttribute("encoding","gbk");
    18. //获取请求调度对象
    19. RequestDispatcher rd = req.getRequestDispatcher("/servletDemo10");
    20. //实现转发功能
    21. rd.forward(req,resp);
    22. }
    23. @Override
    24. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    25. doGet(req,resp);
    26. }
    27. }
    1. package servlet;
    2. import javax.servlet.RequestDispatcher;
    3. import javax.servlet.ServletException;
    4. import javax.servlet.annotation.WebServlet;
    5. import javax.servlet.http.HttpServlet;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;
    8. import java.io.IOException;
    9. /*
    10. 请求转发
    11. */
    12. @WebServlet("/servletDemo10")
    13. public class ServletDemo10 extends HttpServlet {
    14. @Override
    15. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    16. //获取共享数据
    17. Object encoding = req.getAttribute("encoding");
    18. System.out.println(encoding);
    19. System.out.println("servletDemo10执行了...");
    20. }
    21. @Override
    22. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    23. doGet(req,resp);
    24. }
    25. }

    11.请求包含

    在实际开发中,我们可能需要把两个Servlet的内容合并到一起来响应浏览器,而HTTP协议的特点是一请求,一响应的方式

    所以绝对不可能出现有两个Servlet同时响应方式。那么我们就需要用到请求包含,把两个Servlet的响应内容合并输出

    请求包含:可以合并其他 Servlet 中的功能一起响应给客户端

    特点:

            浏览器地址栏不变

            域对象中的数据不丢失

            被包含的 Servlet 响应头会丢失

    返回值方法名说明
    RequestDispatchergetRequestDispatcher(String name)获取请求调度对象
    voidinclude(ServletRequest req,ServletResponse resp)实现包含
    1. package servlet;
    2. import javax.servlet.RequestDispatcher;
    3. import javax.servlet.ServletException;
    4. import javax.servlet.annotation.WebServlet;
    5. import javax.servlet.http.HttpServlet;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;
    8. import java.io.IOException;
    9. /*
    10. 请求包含
    11. */
    12. @WebServlet("/servletDemo11")
    13. public class ServletDemo11 extends HttpServlet {
    14. @Override
    15. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    16. System.out.println("servletDemo11执行了...");
    17. //获取请求调度对象
    18. RequestDispatcher rd = req.getRequestDispatcher("/servletDemo12");
    19. //实现包含功能
    20. rd.include(req,resp);
    21. }
    22. @Override
    23. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    24. doGet(req,resp);
    25. }
    26. }
    1. package servlet;
    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.IOException;
    8. /*
    9. 请求包含
    10. */
    11. @WebServlet("/servletDemo12")
    12. public class ServletDemo12 extends HttpServlet {
    13. @Override
    14. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    15. System.out.println("servletDemo12执行了...");
    16. }
    17. @Override
    18. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    19. doGet(req,resp);
    20. }
    21. }

  • 相关阅读:
    【洛谷 P3853】[TJOI2007] 路标设置 题解(二分答案+递归)
    VOC2012数据集的探索性数据分析(EDA)
    CUDA优化reduce
    关于动态内存管理中的常见练习题
    1166 Summit – PAT甲级真题
    2022 云原生编程挑战赛火热报名中!看导师如何拆解 Serverless 赛题?
    XTU-OJ 1194-Recipient
    【一知半解】AQS
    【数据结构】顺序栈及其基本操作
    ET-B31H-M人员信息导入有哪几种方式?
  • 原文地址:https://blog.csdn.net/weixin_61611746/article/details/132650313