Servlet实现定时跳转

package com.refresh;//这行代码用于自动识别包,并导包

import java.io.IOException;

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

public class Refresh extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//对于get请求的乱码解决,先采用iso8859-1编码,再使用utf-8解码
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//对于post请求,设置请求编码,防止乱码
		request.setCharacterEncoding("utf-8");
		//设置响应正文的编码和浏览器解码采用的编码
		response.setContentType("text/html;charset=utf-8");
		
		//test1(response);
		test2(request,response);
		
	}
	//第一种方式:response设置头信息定时刷新
	private void test1(HttpServletResponse response){
		response.setHeader("refresh", "3;url=/web2/show.jsp");
		try {
			response.getWriter().write("如果没有跳转,请点击这里");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//第二种方式,设置request的属性定时跳转
	private void test2(HttpServletRequest request,HttpServletResponse response){
		String meta="";
		request.setAttribute("meta", meta);
		try {
			request.getRequestDispatcher("/main.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(Servlet)