servletResponse 实用的页面跳转技术和定时刷新技术

package 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 ResponseDemo5 extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        test3(request, response);
    }
    //这种方法开发中常用
    private void test3(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //通过meta标签来模拟页面跳转
        String message = "<meta http-equiv='refresh' content='3;url=/requestandresponse/index.jsp'>恭喜你登录成功,页面将在3秒内跳转,如不跳转请点击<a href=''>超链接</a>";
        this.getServletContext().setAttribute("message", message);
        //页面跳转到jsp页面
        this.getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
    }

    //这种方法在开发中是不用的以为,提示信息是交给jsp页面显示的,不能通过servlet直接显示
    private void test2(HttpServletResponse response) throws IOException {
        //假设这是一个用于处理登录的Servlet
        //假设程序运行到此,用户登录成功了
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("refresh","3;url='/requestandresponse/index.jsp'");
        response.getWriter().write("恭喜你登录成功,页面将在3秒内跳转,如不跳转请点击<a href=''>超链接</a>");
    }
    
    private void test1(HttpServletResponse response) throws IOException {
        //通知浏览器每隔3秒刷新一次
        response.setHeader("refresh","3");
        String data = new Random().nextInt(10000)+"";
        response.getWriter().write(data);
    }

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

}

原文地址:https://www.cnblogs.com/siashan/p/3913304.html