我需要懂得努力

个人知识总结

javaweb之response refresh响应头控制浏览器刷新(几秒后跳转页面)

package test.response;

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//控制浏览器定时刷新,这个经常用,比如股票软件
public class ResponseDemo4 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test3(request, response);
	}

	// 实际开发中实用的,就是用<meta>标签模拟http响应头
	private void test3(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 假设是一个处理用户登录的servlet,假设用户已经成功登录,需要三秒后跳转首页
		// servlet是不适合做数据展现的,所以要在jsp中输出
		String message = "<meta http-equiv='refresh' content='3;url=/day06/index.jsp'/>恭喜您登录成功,将在3秒后跳转到首页,如果没有跳转,请点击<a href=''>超链接</a>";
		request.setAttribute("message", message);
		this.getServletContext().getRequestDispatcher("/message.jsp")
				.forward(request, response);
	}

	private void test2(HttpServletResponse response) throws IOException {
		// 假设是一个处理用户登录的servlet,假设用户已经成功登录,需要三秒后跳转首页
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		response.setHeader("refresh", "3;url='/day06/index.jsp'");
		response.getWriter().write(
				"恭喜您登录成功,将在3秒后跳转到首页,如果没有跳转,请点击<a href=''>超链接</a>");
	}

	private void test1(HttpServletResponse response) throws IOException {
		// 发响应头控制浏览器每隔三秒刷新一次
		response.setHeader("refresh", "3");
		String data = new Random().nextInt(100000000) + "";
		response.getWriter().write(data);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  <body>
  	<%
  		String message = (String)request.getAttribute("message");
  		out.write(message);
  	%>
  </body>
</html>


阅读更多
个人分类: 自己用
上一篇写给自己的javaweb细节
下一篇javaweb之response用Expires头控制浏览器使用缓存
想对作者说点什么? 我来说一句

免费的vpn小白兔软件

2011年06月08日 978KB 下载

没有更多推荐了,返回首页

关闭
关闭