当前位置:首页 > JSP教程 > JSP基础教程

JSP页面重定向

在本章中,我们将讨论使用jsp的页面重定向。 通常在文档移动到新位置时使用页面重定向,我们需要将客户端发送到此新位置。这可能是因为负载平衡,或者是简单的随机化。

将请求重定向到另一个页面的最简单的方法是使用响应对象的sendredirect()方法。 以下是这种方法的签名 -

public void response.sendredirect(string location)
throws ioexception

该方法将响应与状态代码和新页面位置一起发送回浏览器。也可以一起使用setstatus()和setheader()方法来实现相同的重定向示例 -

....
string site = "http://www.51frw.cn" ;
response.setstatus(response.sc_moved_temporarily);
response.setheader("location", site); 
....

重定向示例

打开eclipse,创建一个动态web工程:redirect,并在这个项目中创建示例jsp文件。

此示例显示jsp如何执行页面重定向到另一个位置( http://www.51frw.cn)。

文件:pageredirect.jsp -

<%@ page language="java" contenttype="text/html; charset=utf-8"
    pageencoding="utf-8"%>
<%@ page import="java.io.*,java.util.*"%>

<!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>页面重定向示例</title>
</head>
<body>
    <center>
        <h1>页面重定向示例</h1>
    </center>
    <%
        // new location to be redirected
        string site = new string("http://www.51frw.cn");
        response.setstatus(response.sc_moved_temporarily);
        response.setheader("location", site);
    %>
</body>
</html>

编写完成上面代码,部署项目。然后打开浏览器访问url: http://localhost:8080/redirect/pageredirect.jsp 调用此jsp。这将自动定向到到给定的url: http://www.51frw.cn。


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!