请求重定向和请求转发

请求转发:

1、请求转发只会发起一次请求

2、请求转发浏览器地址栏不会发生改变

3、请求转发request对象是同一个

4、请求转发可以访问web-inf目录,但是不可以访问外网

5、请求转发不需要加应用名

6、请求转发不适合支付功能

重定向

1、重定向会发起两次 请求

2、重定向地址栏会发生改变

3、重定向request对象不是同一个

4、重定向不可以访问web-inf,但是可以访问外网

5、重定向需要加上应用名

案例说明:这里我配置的应用名是/servlet

请求重定向和请求转发_第1张图片

1、请求转发 

@WebServlet(urlPatterns = {"/hi"})
public class HiServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/hello").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

@WebServlet(urlPatterns = {"/hello"})
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("请求转发");
        writer.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

请求转发时序图 

请求重定向和请求转发_第2张图片

2、请求重定向

@WebServlet(urlPatterns = {"/hi"})
public class HiServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/servlet/hello");
        
        //第二种写法
        //resp.setStatus(302);
        //resp.setHeader("Location","/servlet/hello");

        //第三种写法
        //String contextPath = getServletContext().getContextPath();
        //resp.sendRedirect(contextPath+"/hello");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

@WebServlet(urlPatterns = {"/hello"})
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("请求重定向");
        writer.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

请求重定向时序图 

请求重定向和请求转发_第3张图片

你可能感兴趣的:(servlet,servlet)