请求转发(forward):一种服务器内部的资源跳转方式
实现方式:
创建两个Servlet,并配置他们的访问路径
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@WebServlet("/d3")
public class ServletForward3 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("d3.........");req.getRequestDispatcher("/d4").forward(req,resp);}}
通过上面的程序,请求转发给下面的程序
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@WebServlet("/d4")
public class ServletForward4 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("d4.......");}}
最后输出 d3.........
d4............
请求转发资源之间共享数据:使用Request对象
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@WebServlet("/d3")
public class ServletForward3 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("d3.........");req.setAttribute("张三","男");req.getRequestDispatcher("/d4").forward(req,resp); //数据存入域}
}
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@WebServlet("/d4")
public class ServletForward4 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("d4.......");System.out.println(req.getAttribute("张三"));// 通过键获取域中的值}}
最后输出 :男
共享数据就成功了
请求转发的特点:
浏览器地址栏路径不发生变化
只能请求转发到当前服务器的内部资源
一次请求,可以转发的资源之间使用request共享数据
本文链接:https://my.lmcjl.com/post/1917.html
展开阅读全文
4 评论