虚拟目录(项目路径访问):加上了模块名:/request-demo/resp2 — 其中的/request-demo是模块名,就是虚拟目录,用于浏览器使用
    URL名:去掉模块名: /resp2
    image.png

    1. package com.itheima.web.reponse;
    2. import javax.servlet.*;
    3. import javax.servlet.http.*;
    4. import javax.servlet.annotation.*;
    5. import java.io.IOException;
    6. @WebServlet("/resp1")
    7. public class ResponseDemo1 extends HttpServlet {
    8. @Override
    9. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    10. System.out.println("resp1...");
    11. // 将resp1 重定向到resp2
    12. // 1. 设置响应状态码 302
    13. // response.setStatus(302); // 302 从重定向状态码
    14. // // 2. 设置响应头 Location 第二个参数为虚拟目录(模块名 + resp的目录)
    15. // response.setHeader("Location","/request-demo/resp2");
    16. // 简化方式完成重定向
    17. //动态获取虚拟目录
    18. String contextPath = request.getContextPath();
    19. // 简化方式完成重定向
    20. response.sendRedirect(contextPath + "/resp2"); // 这是一个明确路径,
    21. // 也可以重定向到百度
    22. // response.sendRedirect("https://www.baidu.com");
    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.reponse;
    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("/resp2")
    9. public class ResponseDemo2 extends HttpServlet {
    10. @Override
    11. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    12. System.out.println("resp2...");
    13. }
    14. @Override
    15. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    16. this.doGet(request, response);
    17. }
    18. }