实现请求重定向的思路:
具体代码:
第一种方法(不推荐):
Servlet1.java:
package demo01; 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; /** * 用于实现请求重定向 第一种方法(不推荐) */ public class Response1 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("这是response1!"); //设置响应状态码302,表示已搬迁(已搬迁) response.setStatus(302); //设置响应头,说明新的地址在哪里 response.setHeader("location","http://localhost:8080/draft_war_exploded/response2"); } }
Servlet2.java:
package demo01; 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; /** * 用于实现请求重定向 第一种方法(不推荐) */ public class Response2 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("GBK"); response.getWriter().write("这是servlet2"); } }
第二种方法(推荐):
Servlet2.java代码不变,Servlet3.java代替Servlet1.java
Servlet3.java:
package demo01; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 用于实现请求重定向 第二种方法(推荐) */ public class Response3 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("这是response1!"); response.sendRedirect("http://localhost:8080/draft_war_exploded/response2"); } }
运行一下试一试:
浏览器中访问servlet1,按回车之后,显示servlet2的页面,并且路径也发生变化
访问servlet3也是如此。