一、介绍
所谓请求重定向,指的是Web服务器接收到客户端的请求后,可能由于某些条件限制,不能访问当前请求URL所指向的Web资源,而是指定了一个新的资源路径,让客户端重新发送请求。
为了实现请求重定向,在HttpServletResponse接口中,定义了一个sendRedirect()方法,该方法用于生成302响应码和Location响应头,从而通知客户端重新访问Location响应头中指定的URL,sendRedirect()方法的完整语法如下所示:
public void sendRedirect(String location) throws IOException;
需要注意的是,参数location可以使用相对URL,Web服务器会自动将相对URL翻译成绝对URL,再生成Location头字段。
为了使读者更好地了解sendRedirect()方法如何实现请求重定向,接下来,通过一个图来描述sendRedirect()方法的工作原理,如图所示。
在图中,当客户端访问Servlet1时 ,由于在Servlet1中调用了sendRedirect()方法将请求重定向到Servlet2,因此,客户端在收到Servlet1的响应消息后,立刻向Servlet2发送请求。Servlet2对请求处理完毕后,再将响应消息回送给客户端。
二、登录案例
1.需求
如果用户名和密码正确,重定向到 welcome.html,否则重定向到login.html
2.编写登录页面和欢迎页面
login.html
<!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>
<!--把表单内容提交到chapter04工程下的LoginServlet-->
<form action="/chapter04/LoginServlet" method="post">
用户名: <input type="text" name="username" /><br>
密 码: <input type="password" name="password" /><br>
<input type="submit" value="登录" />
</form>
</body>
</html>
welcome.html
<!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>
欢迎你,登录成功!
</body>
</html>
3.LoginServlet
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
// 用HttpServletRequest对象的getParameter()方法获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 假设用户名和密码分别为:aaa和123
if (("aaa").equals(username) && ("123").equals(password)) {
// 如果用户名和密码正确,重定向到 welcome.html
response.sendRedirect("/chapter04/welcome.html");
} else {
// 如果用户名和密码错误,重定向到login.html
response.sendRedirect("/chapter04/login.html");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}