使用request对象中的sendRedirect()方法实现重定向(网页跳转)到另一个页面。
格式:request.sendRedirect("*.jsp");
与转发1a8eea67b160d30d77aad2a336de16ad的区别:前者可以跳转到任一个地址的页面,后者只能在本网站内跳转。前者带着request中的信息跳 转,后者不带。
示例:用户在登录界面输入登录名和密码,输入正确和错误分别跳转到不同的页面。
代码:
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中文网其他相关文章!