HttpServletResponse中的请求重定向sendRedirect()方法和刷新setHeader()方法


1,setHeader()方法

用setHeader()方法设置响应头,为刷新“refresh”,然后设置几秒后刷新的时间和url地址

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	
		//设置返回客户端的编码
		response.setContentType("text/html;charset=UTF-8");
		/*response.setIntHeader("refresh", 1);//设置1秒钟刷新一次
		
		Random r = new Random();
		
		response.getWriter().write(r.nextInt()+"");*/
		
		response.getWriter().write("注册成功!3秒钟跳到主页");
		//设置3秒钟跳转
		response.setHeader("refresh", "3;url=/day09_00_HttpServletResponse/servlet/demo6");
	}



2,sendRedirect()方法请求重定向response.sendRedirect("/day09_00_HttpServletResponse/servlet/demo8");然后就会重新定向到相应的servlet

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("A:我要借钱!");
		System.out.println("B:我不有,但是我可以告诉你谁有");
		/*//告诉客户端要重新定向新的资源
		response.setStatus(302);
		//告诉浏览器要去访问哪个URL
		response.setHeader("location", "/day09_00_HttpServletResponse/servlet/demo8");*/
		
		//请求重定向
		response.sendRedirect("/day09_00_HttpServletResponse/servlet/demo8");
		
		System.out.println("A: 我去了");
		
	}



重定向到的页面/servlet/demo8

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("我有钱,我借你!");
	}



结果最后重定向的结果如下

HttpServletResponse中的请求重定向sendRedirect()方法和刷新setHeader()方法_第1张图片

你可能感兴趣的:(重定向,刷新,刷新setHeader方法)