当执行到<jsp:forward page="相对路径"></jsp:forward>后,会立即结束当前页面的显示,跳转到另一个页面(JSP、HTML、Servlet类)。
1、不带参数的forward标签:
定义jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>jsp的学习</title> </head> <body> 今天是国庆假期的第二天。 <jsp:forward page="forward.jsp"></jsp:forward> 今天是国庆假期的第二天。 </body> </html>.
定义要跳转到的jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>forward</title> </head> <body> <h3>我是forward跳转后的页面!</h3> </body> </html>
跳转后访问的地址没有改变,与请求转发类似。
注意事项:
标签:<jsp:forward page="相对路径"></jsp:forward>中间不能有空格
2、带参数的forward标签:
设置forward标签的键和值:
<%@ page contentType="text/html;charset=utf-8" language="java" %> <html> <head> <title>jsp的学习</title> </head> <body> <jsp:forward page="forward.jsp"><jsp:param name="1" value="123"></jsp:param></jsp:forward> </body> </html>.
由键获取值:
<html> <head> <title>forward</title> </head> <body> <h3>我是forward跳转后的页面!</h3> <h2>从index.jsp获取到的值为:<%=request.getParameter("1")%></h2> </body> </html>
3、forward标签在登录界面的应用:
log.jsp实现对用户信息的收集:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body bgcolor="aqua"> <center> <h3>登录</h3> <form method="get" action="check.jsp"> 用户名:<input type="text" name="username" size="12"><br> 密 码 :<input type="password" name="password" size="6" ><br><br> <input type="reset" value="取消"> <input type="submit" value="登录"> </form> </center> </body> </html>
check.jsp对用户提交的信息进行校验:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>check</title>
</head>
<body>
<%
String name=request.getParameter("username");
String password=request.getParameter("password");
if(name.equals("zhai")&&password.equals("1997")){
%>
<jsp:forward page="success.jsp">
<jsp:param name="username" value="<%=name%>"></jsp:param>
</jsp:forward>
<%
}
else {
%>
<jsp:forward page="log.jsp"></jsp:forward>
<%
}
%>
</body>
</html>
此jsp实现了从log.jsp获取用户信息,并将信息封装在forward内,在页面跳转后,能够通过键获取相应的值。
success.jsp:实现登录成功后的信息显示,获取到了forward内部的信息:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>success</title> </head> <body> <h3>登录成功,欢迎你:<%=request.getParameter("username")%></h3> </body> </html>
4、useBean标签
(1)创建一个javaBean:
public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User [username=" + username + ", password=" + password + "]"; } }
用普通的方式创建User对象并对一个对象进行初始化:
<% User user=new User(); user.setUsername("zhai"); user.setPassword("123zhi"); out.println(user.toString()); %>
用标签进行赋值并取出值:
<jsp:useBean id="user1" class="pers.zhb.domain.User" scope="page">
<jsp:setProperty property="username" name="user1" value="hello"/>
<jsp:getProperty property="username" name="user1"/>