(二十一):设置页面跳转 (JSP学习第六天)

设置页面跳转

使用response对象中的sendRedirect()方法进行跳转

直接跳转到hello.html页面 response_demo03.jsp

<%@ page language="java" contentType="text/html" pageEncoding="GBK"%>
<html>
<head>
<title>测试</title>
</head>
<body>
<%
 response.sendRedirect("hello.html");
%>
</body>
</html>

这种跳转属于客户端跳转

<jsp:forward>属于服务端跳转,地址不会发生改变,可以将request属性保存到跳转页
response.sendRedirect()属于客户端跳转,地址会发生改变,不可以将request属性保存到跳转页
还有一个区别就是:服务端跳转会立刻跳转,而客户端跳转在整个页面执行完后才进行跳转

服务器端跳转response_demo04.jsp

<%@ page language="java" contentType="text/html" pageEncoding="GBK"%>
<html>
<head>
<title>测试</title>
</head>
<body>
<%
 System.out.println("----------forward跳转之前的-------------");
%>
<jsp:forward page="hello.html"/>
<%
 System.out.println("----------forward跳转之后的-------------");
%>
</body>
</html>

 

显示结果:hello
但tomcat服务器后台显示----------forward跳转之前的-------------

客户端跳转 response_demo05.jsp

<%@ page language="java" contentType="text/html" pageEncoding="GBK"%>
<html>
<head>
<title>测试</title>
</head>
<body>
<%
 System.out.println("----------response跳转之前-------------");
%>
<%
 response.sendRedirect("hello.html");
%>
<%
 System.out.println("----------response跳转之后------------");
%>
</body>
</html>

tomcat服务器后台显示----------response跳转之前-------------
     ----------response跳转之后-------------
     
由于这两种跳转存在差异,所以在开发中,使用JDBC操作中,一定要再<jsp:forward>语句之
前关闭数据库的连接否则再也无法关闭,如果没有关闭,将达到一定程度时,则会出现数据库
已经达到最大的异常,此时就只有重启服务器了

使用<jsp:forward>,可以通过<jsp:param>进行参数传递
而使用response.sendRedirect()方式传递只有通过地址重写的方式传递
所以服务端跳转比客户端跳转更常用!

posted @ 2011-10-06 15:58  techstan  阅读(2177)  评论(0编辑  收藏  举报