forward 标签是用于请求转发到另一个页面的。
基本用法:<jsp:forward page="跳转的文件"></jsp:forward>
下面给一个浏览器登录的例子:
(若用户名密码正确,则跳转到成功页面,否则,跳转到失败页面)
登录界面:
成功登录界面:
例子代码:
三个文件: login.jsp,success.jsp,fail.jsp
目录树:
login.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<form action="/JSPDEMO/login.jsp" method="post">
<input type="hidden" name="isSubmit" value="1">
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
<input type="submit" value="submit">
</form>
<%
String isSubmit = request.getParameter("isSubmit");
if("1".equals(isSubmit)){
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username.equals("zje") && password.equals("123")){
request.setAttribute("userInfo", username+"你好!");
%>
<jsp:forward page="/success.jsp"></jsp:forward>
<%
}else{
%>
<jsp:forward page="/fail.jsp"></jsp:forward>
<%
}
}
%>
</body>
</html>
11~16行是设置一个表单,设定输入控件,用于输入用户名和密码
12行,是设置一个隐藏的控件,实质是结合19~20行,用于让11~16先运行。
24行,是当登录成功时,把用户名作为一个request属性,传给将要跳转到的 success.jsp,好让success.jsp能够打印用户名(这操作不是必要的)
success.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<%
String userInfo = (String)request.getAttribute("userInfo");
%>
<h1>登录成功!</h1><br>
<h1><%=userInfo %></h1>
</body>
</html>
12行,是获取(由login.jsp)传进来的属性参数
fail.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<h1>用户名或密码错误!</h1>
</body>
</html>
浏览器打印:用户名或密码错误!