[JSP] 实现请求重定向

在服务器端, 对客户端的请求进行重新的定向, 请注意请求重定向和请求转发的区别;

用三个jsp网页演示请求重定向:

redirect1.jsp 用来向redirect2.jsp提交表单, redirect1.jsp的代码为:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Redirect1</title>
</head>
<body>
<h1>Redirect1</h1>
<form action="redirect2.jsp" method="post">
姓名:
<input type="text" name="username"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>

redirect2.jsp用来实现重定向, 代码为:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Redirect2</title>
</head>
<body>
<h1>Redirect2</h1>
<%
response.sendRedirect(
"redirect3.jsp");
%>
</body>
</html>

redirect3.jsp用来显示表单数据, 代码为:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>redirect3</title>
</head>
<body>
<h1>redirect3</h1>
<%String username = request.getParameter("username"); %>

用户名为:
<%=username %>
</body>
</html>

向表单里输入数据后, 点击提交, 会发现 在返回的页面中, 原来应该显示表单数据的地方却显示 "null", 这个是正确的了.

因为重定向的原理是:  客户端发送请求--->服务器-----"服务器调用"response.sendRedirect()"方法返回给客户端"--->客户端---"客户端再次向服务器发出请求"--->服务器--->客户端

所以在这一过程中, 客户端进发出两次请求, 所以才会显示"null".

在重定向这一过程中, request的 getParameter() 方法和 getAttributer()方法是无效的.

要特别注意请求重定向和请求转发的区别.

 

posted @ 2011-07-30 16:42  ShanHaiyang  阅读(2363)  评论(0编辑  收藏  举报