使用request物件中的sendRedirect()方法實作重定向(網頁跳轉)到另一個頁面。
格式:request.sendRedirect("*.jsp");
##與轉送
範例:使用者在登入介面輸入登入名稱和密碼,輸入正確和錯誤分別跳到不同的頁面。
程式碼:
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'login.jsp' starting page</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> <form action="receive.jsp" method="post"> 姓名:<input type="text" name="rdname"><br> 密码:<input type="text" name="rdpasswd"><br> <input type="submit" value="确定"> </form> </body> </html
receive.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'receive.jsp' starting page</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> <% String name=request.getParameter("rdname"); String passwd=request.getParameter("rdpasswd"); if(name.equals("abcd")&&passwd.equals("123456")){ %> <jsp:forward page="correct.jsp"/> <%}else{%> <% response.sendRedirect("http://sohu.com");}%> </body> </html>correct.jsp
##<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'correct.jsp' starting page</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>
<% String name=request.getParameter("rdname"); %>
欢迎,<%=name %>成功登陆!
</body>
</html>
執行結果(正確):
執行結果(錯誤):
以上是jsp如何重新導向網頁的詳細內容。更多資訊請關注PHP中文網其他相關文章!