实现请求重定向

一、介绍

        所谓请求重定向,指的是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>
		密  &nbsp;&nbsp;&nbsp;码:   <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);
	}
}

 4.运行

http://localhost:8080/javawebproject/login.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值