博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于java中sendRedirect,forward和include区别
阅读量:4358 次
发布时间:2019-06-07

本文共 2042 字,大约阅读时间需要 6 分钟。

在javaWeb中页面跳转一般有三种形式,sendRedirect,forward和include,三者有什么区别呢?

我先进行说明,再以一个小例子说明

一、sendRedirect

使用方式

response.sendRedirect();

服务器根据逻辑,发送一个状态码,告诉浏览器去请求指定的地址,把需要的参数放在转发的地址里面。由于是一次新的申请,原先的request就不能读取了,可以使用session代替,或者使用include,和forward代替

二、forward

使用方式

request.getRequestDispatcher("/first.jsp").forward(request, response);

页面会是first.jsp的内容,地址栏不变

可以使用设置属性

三、include

使用方式

request.getRequestDispatcher("/first.jsp").include(request, response);

页面会同时包含当前页面和first.jsp的内容

可以使用设置属性

 

下面是一个例子

index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" %>
Insert title here

index.jsp 页面

first.jsp
first.jsp带id123456
second.jsp
second.jsp带id123456
third.jsp
third.jsp带id123456
可以获取id为:<%=request.getParameter("id") %>

first.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" %>
Insert title here

first.jsp 页面

提交的ID:<%=request.getParameter("id")%> <% response.sendRedirect(request.getContextPath()+"/index.jsp"); System.out.println("first.jsp有访问过了"); %>

second.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" %>
Insert title here

second.jsp 页面

<% request.getRequestDispatcher("/index.jsp").forward(request, response);%>提交的ID:<%=request.getParameter("id")%>

third.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" %>
Insert title here

third.jsp 页面

提交的ID:<%=request.getParameter("id")%><% request.getRequestDispatcher("/fourth.jsp").include(request, response); request.getRequestDispatcher("/index.jsp").include(request, response);%>

fourth.jsp 

<%@ page language="java" contentType="text/html; charset=utf-8" %>
Insert title here

fourth.jsp 页面


接下来运行服务器(使用的是TomCat8.0)

访问项目

点击第一个链接

 

页面没有变化,但是控制台有输出,表示访问过了

我们试着传一个参数过去id=123456

不能获取id,说明是浏览器重新发出的一个请求,request已经被销毁,这个是一个新的request

下面放上流程图

点击第三个连接

页面没有变化,但是地址栏发生变化

我们传一个参数进去

有了,可以显示id,说明是同一个request

下面放上流程图

因为forward是服务器内部跳转,会带着request一起到下一个页面,所以id可以获得

接着点击第五条链接

页面发生变化,同时包含了,third.jsp和fourth.jsp的内容

我们传一个参数

可以获得request

下面是流程图

本人知识有限,如有错误,望指出

此文系原创,转载请声明出处。

转载于:https://www.cnblogs.com/sean1009/p/5351660.html

你可能感兴趣的文章
Android ViewDragHelper全然解析 自己定义ViewGroup神器
查看>>
c++ 基础 const char* 转 char*
查看>>
JS-- 小细节--你悟到了什么?
查看>>
收款 借贷
查看>>
Gson关于抽象类的序列化与反序列化
查看>>
Java面向对象之类和对象
查看>>
Oracle数据库提权(dba权限执行系统命令)
查看>>
Hydra爆破神器使用
查看>>
java.util.zip.ZipException: duplicate entry(重复依赖多版本的类库)
查看>>
Run MVC in older version of IIS
查看>>
Ajax 监听
查看>>
隐藏"站长统计"图标
查看>>
Oracle select 中case 的使用以及使用decode替换case
查看>>
创建一个dynamics 365 CRM online plugin (十二) - Asynchronous Plugins
查看>>
Eclipse 常用快捷键 (动画讲解)
查看>>
233 Matrix(矩阵快速幂+思维)
查看>>
Leetcode-Unique Binary Search Trees II
查看>>
Centos7系统下安装Docker
查看>>
PostgreSQL 序列(SEQUENCE)
查看>>
Missing Number
查看>>