dispatcher 调度的意思 [dɪˈspætʃər]
    Attribute 属性的意思 [ ˈætrɪbjuːt]
    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.IOException;
    8. import java.nio.charset.StandardCharsets;
    9. /**
    10. * 请求转发
    11. */
    12. @WebServlet("/req5")
    13. public class RequestDemo5 extends HttpServlet {
    14. @Override
    15. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    16. System.out.println("demo5...");
    17. // 存储数据 存储一个键值对的数据,存储到request对象当中,然后会随着下面的forward转发到req6中
    18. request.setAttribute("msg","hello"); // 第一个参数写数据名,后面接数据内容
    19. // 请求转发: 将对应的demo5 的 request 和response对象转发过去
    20. // 第一个参数填:需要转发的路径(填demo6.java的虚拟路径)
    21. // 第二个参数填: 需要转发的对象
    22. request.getRequestDispatcher("/req6").forward(request,response);
    23. }
    24. @Override
    25. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    26. this.doGet(request, response);
    27. }
    28. }
    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.IOException;
    8. /**
    9. * 请求转发
    10. */
    11. @WebServlet("/req6")
    12. public class RequestDemo6 extends HttpServlet {
    13. @Override
    14. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    15. System.out.println("demo6...");
    16. //获取数据
    17. Object msg = request.getAttribute("msg"); // 根据数据名得到数据类型
    18. System.out.println(msg);
    19. }
    20. @Override
    21. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    22. this.doGet(request, response);
    23. }
    24. }