1.重定向。
关键点:2次请求。
client请求A资源,A资源返回302,还有B的地址。client请求B。
BServlet中的代码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Location", "/HelloWorld/CServlet"); response.setStatus(302);
注意重定向位置是相对于主机的,比如localhost:8080
BServlet回复内容:
HTTP/1.1 302 Found
Server: Apache-Coyote/1.1
Location: /HelloWorld/CServlet
Content-Length: 0
Date: Fri, 08 Jun 2018 12:43:09 GMT
然后客户端就按照地址直接访问CServlet去了。
1.1延时重定向
访问后,客户端等待几秒后再重定向。BServlet代码如下
PrintWriter w=response.getWriter(); w.print("welcome to this page..Redirect in 5 seconds.?"); response.setHeader("Refresh", "5;URL=/HelloWorld/CServlet");
客户端访问BServlet,BServlet返回
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Refresh: 5;URL=/HelloWorld/CServlet
Content-Length: 50
Date: Fri, 08 Jun 2018 13:19:37 GMT
welcome to this page..Redirect in 5 seconds.
客户端5秒后访问CServlet