package com.learn.day06.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; /** * @ClassName: ResponseDemo5 * @Description: 设置页面自动刷新 * @author amosli * @date 2013-10-16 下午11:57:08 * */ public class ResponseDemo5 extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test2(request, response); } public void test2(HttpServletRequest request, HttpServletResponse response) throws IOException { //用meta标签模拟一个头 try { String message = "<meta http-equiv='refresh' content='3;url=/servlet_learn_day06_0905/index.jsp'>恭喜您,注册成功!本页面将在3秒后自动跳转到首页!如果没有跳转请手动点击<a href=''>超链接</a>"; // 跳转,通过servletContext实现跳转 this.getServletContext().setAttribute("message", message); this.getServletContext().getRequestDispatcher("/message.jsp").forward(request, response); } catch (ServletException e) { e.printStackTrace(); } } public void test1(HttpServletResponse response) throws IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); response.setHeader("refresh", "3;url='/servlet_learn_day06_0905/index.jsp'"); response.getWriter().write("恭喜您,注册成功!本页面将在3秒后自动跳转到首页!如果没有跳转请手动点击<a href=''>超链接</a>"); } public void test(HttpServletResponse response) throws IOException { response.setHeader("refresh", "3"); String dataString = new Random().nextInt(10) + ""; response.getOutputStream().write(dataString.getBytes()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
message.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% String message= (String )application.getAttribute("message"); System.err.println(message); out.write(message); %> </body> </html>