標籤:
forward指令 既可以指向靜態html頁面,也可以轉寄到動態jsp頁面,並可以保留先前請求的參數.
例如,在web中建立一個Jsp_src.jsp的jsp頁面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>原始頁面</title> <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--> </head> <body> 原始頁面. <br> <jsp:forward page="jsp_target.jsp"></jsp:forward> </body></html>
然後讓頁面Jsp_src.jsp轉到jsp_target.jsp頁面,jsp_target.jsp頁面的代碼為:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>jsp目標頁面</title> <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--> </head> <body> 目標頁面主體. <br> <jsp:forward page="jsp_target2.jsp"></jsp:forward> </body></html>
然後,再次在jsp_target.jsp頁面中轉到新的jsp頁面jsp_target2.jsp,代碼為:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>jsp目標頁面2</title> <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--> </head> <body> 目標頁面主體2. <br> req-char:<%=request.getCharacterEncoding() %> name=<%=request.getParameter("name") %> </body></html>
往瀏覽器中輸入請求url: http://localhost:8080/ServletJSP/forward/Jsp_src.jsp?name=hi
可以看到,瀏覽器中請求地址依然不變,但內容也變為jsp_target2.jsp的頁面的內容,而且,請求的參數name仍然可以保留.
jsp - forward指令