欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Servlet之间跳转方案汇总

程序员文章站 2022-03-13 12:07:06
...

实现功能:当用户请求BServlet,BServlet执行完业务操作后,最终跳转到AServlet,进而执行AServlet中的业务。

AServlet

@WebServlet(urlPatterns = "/a")
public class AServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("aaaaa");
    }
}

BServlet

方案一:使用response重定向

@WebServlet(urlPatterns = "/b")
public class BServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("bbbbb");
        response.sendRedirect("a");
    }
}

方案二:请求转发

@WebServlet(urlPatterns = "/b")
public class BServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("bbbbb");
        request.getRequestDispatcher("a").forward(request,response);
    }
}

方案三:页面刷新

@WebServlet(urlPatterns = "/b")
public class BServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("bbbbb");
        response.setHeader("refresh","0;url=a");
    }
}