请求转发的定义:
这是一种在服务器内部的资源跳转方式.(换言之,请求转发是不能跳到服务器之外的资源)
重要用途
1.把任务分布在不同的内部资源中完成
2.可以通过request在不同资源中实现资源的传递,因为请求转发是使用同一个请求
特点:
1.浏览器地址栏路径不发生变化
2.只能转发到当前服务器的内部资源中
3.转发只是一次请求(不过是内部发出的)
请求转发模拟
public class Servlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取请求的参数
String username = request.getParameter("username");
// 查看参数
System.out.println("获取到的请求参数为:"+username);
System.out.println(" 一系列操作...");
//添加域数据,相当于给材料盖章
request.setAttribute("key","true");
// 问路Servlet2怎么走,请求转发必须要以 / 打头 表示地址为http://ip:port/工程名/,映射到idea代码的web目录
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Servlet2");
// 得到跳转对象,并开始开始跳转
requestDispatcher.forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
public class Servlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取请求参数
String username = request.getParameter("username");
// 查看是否有servlet1的域数据
Object key = request.getAttribute("key");
System.out.println("查看是否有servlet1的域数据:"+key);
System.out.println("一系列操作");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
简单对页面进行请求转发
servlet程序
public class Servlet_forC extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 转发请求
System.out.println("经过了Servlet_forC程序");
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/dd/a.html");
requestDispatcher.forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
主页
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
</head>
<body>
这是主页
<a href="./dd/a.html">跳转到./dd/a.html</a> <br>
<a href="http://localhost:8888/servelet_2_war_exploded/Servlet_forC">请求转发</a>
</body>
</html>
跳转的页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>dd下的a.html</title>
<!-- base标签设置页面相对路径工作时参照的地址 -->
<base href="http://localhost:8888/servelet_2_war_exploded/dd/a.html">
</head>
<body>
<a href="../index.jsp">跳转回主页</a>
</body>
</html>
如果没有使用base标签,又因为请求转发不会改变地址栏的信息,所以这时候跳转回首页的相对路径就是以Servlet的地址为基础来进行的,这时候就会出现错误的跳转地址