request请求转发、response重定向跳转
1.用request方法将 Servlet01页面跳转到Servlet02页面
public class Servlet01 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //向request01存值 request.setAttribute("name","詹姆斯"); //请求转发 request.getRequestDispatcher("/Servlet02").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
public class Servlet02 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //request02取值 取得是object的值 需要强转 String name = (String)request.getAttribute("name"); //解决响应乱码 response.setContentType("text/html;charset=utf-8"); response.getWriter().write(name); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
运行结果如下:
2.response重定向跳转
public class Servlet01 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //跳转 response.sendRedirect("/WEB03/Servlet02"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
public class Servlet02 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("okokok"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
运行结果如下:
欢迎各位大神指点和评论;