当前位置 : 主页 > 网页制作 > HTTP/TCP >

Response案例1_重定向

来源:互联网 收集:自由互联 发布时间:2021-06-16
1 import javax.servlet.ServletException; 2 import javax.servlet.annotation.WebServlet; 3 import javax.servlet.http.HttpServlet; 4 import javax.servlet.http.HttpServletRequest; 5 import javax.servlet.http.HttpServletResponse; 6 import java.i
 1 import javax.servlet.ServletException;
 2 import javax.servlet.annotation.WebServlet;
 3 import javax.servlet.http.HttpServlet;
 4 import javax.servlet.http.HttpServletRequest;
 5 import javax.servlet.http.HttpServletResponse;
 6 import java.io.IOException;
 7 
 8 /**
 9  * @Author: 艾康
10  * @Date: 2019/10/15 23:13
11  */
12 
13 /**
14  * 重定向
15  */
16 @WebServlet("/servlettest1")
17 public class ServletTest1 extends HttpServlet {
18     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19         //重定向:资源跳转方式
20         System.out.println("111111111");
21         //1.设置状态码为302
22         response.setStatus(302);
23         //2.告诉浏览器跳转资源路径,使用响应头localhost:跳转的资源路径 设置响应头
24 
25         response.setHeader("location","/Case1/servlettest2");
26 
27     }
28 
29     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
30     this.doPost(request,response);
31     }
32 }

简化代码:

 1 import javax.servlet.ServletException;
 2 import javax.servlet.annotation.WebServlet;
 3 import javax.servlet.http.HttpServlet;
 4 import javax.servlet.http.HttpServletRequest;
 5 import javax.servlet.http.HttpServletResponse;
 6 import java.io.IOException;
 7 
 8 /**
 9  * @Author: 艾康
10  * @Date: 2019/10/15 23:13
11  */
12 
13 /**
14  * 重定向
15  */
16 @WebServlet("/servlettest1")
17 public class ServletTest1 extends HttpServlet {
18     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19         //重定向:资源跳转方式
20         System.out.println("111111111");
21         //1.设置状态码为302
22         response.setStatus(302);
23         //2.告诉浏览器跳转资源路径,使用响应头localhost:跳转的资源路径 设置响应头
24         // response.setHeader("location","/Case1/servlettest2");
25         //简化代码
26         response.sendRedirect("/Case1/servlettest2");
27 
28     }
29 
30     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
31     this.doPost(request,response);
32     }
33 }

 重定向特点:

  1.地址栏发生变化

  2.重定向可以访问其他站点的资源

  3.重定向是两次请求

网友评论