虚拟目录(项目路径访问):加上了模块名:/request-demo/resp2 — 其中的/request-demo是模块名,就是虚拟目录,用于浏览器使用
URL名:去掉模块名: /resp2
package com.itheima.web.reponse;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/resp1")
public class ResponseDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("resp1...");
// 将resp1 重定向到resp2
// 1. 设置响应状态码 302
// response.setStatus(302); // 302 从重定向状态码
// // 2. 设置响应头 Location 第二个参数为虚拟目录(模块名 + resp的目录)
// response.setHeader("Location","/request-demo/resp2");
// 简化方式完成重定向
//动态获取虚拟目录
String contextPath = request.getContextPath();
// 简化方式完成重定向
response.sendRedirect(contextPath + "/resp2"); // 这是一个明确路径,
// 也可以重定向到百度
// response.sendRedirect("https://www.baidu.com");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
package com.itheima.web.reponse;
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;
@WebServlet("/resp2")
public class ResponseDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("resp2...");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}