Jsp 中转发与重定向的区别

xiaoxiao2021-02-28  88

问题:要在 b.jsp 中获取 a.jsp 中设置的变量值,通过重定向的话会丢失 request 数据,而通过转发则不会丢失 request 数据。

a.jsp 文件代码如下:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <% /** 转发:响应请求后地址不变,request数据不丢失,因为request数据只能在同一请求中有效,转发是在服务器内部完成的。 重定向:响应请求后地址改变,request数据丢失,发了两个请求,转发是在服务器外部完成的。 */ request.setAttribute("user","易斌"); //转发(在 b.jsp中可以获取到 user 的值) request.getRequestDispatcher("b.jsp").forward(request,response); //重定向(在 b.jsp中获取不到 user 的值) //response.sendRedirect("b.jsp"); %> </body> </html> b.jsp 文件的代码:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <% String user = (String)request.getAttribute("user");//强制类型转换为String out.print(user); %> </body> </html> 原理图如下所示:

结论:request 请求的数据只在同一个请求中存在。所以只能使用 转发 而不是 重定向。

转载请注明原文地址: https://www.6miu.com/read-75941.html

最新回复(0)