~本特利~ |
实现请求重定向
请求重定向,是指客户端给服务器发请求,然后服务器告诉客户端说。我给你一些地址。你去新地址访问。叫请求重定向(因为之前的地址可能已经被废弃)。
1.在项目下编写登录页面login.html和登录成功页面welcome.html
login.html如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--把表单内容提交到Demo04工程下的LoginServlet-->
<form action="/Demo04/LoginServlet" method="post">
用户名: <input type="text" name="username" /><br>
密 码: <input type="password" name="password" /><br>
<input type="submit" value="登录" />
</form>
</body>
</html>
welcome.html如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
欢迎你,登录成功!
</body>
</html>
2.项目的包里编写名为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");
// 假设用户名和密码分别为:root和123
if (("root").equals(username) &&("123").equals(password)) {
// 如果用户名和密码正确,重定向到 welcome.html
response.sendRedirect("/Demo04/welcome.html");
} else {
// 如果用户名和密码错误,重定向到login.html
response.sendRedirect("/Demo04/login.html");
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
doGet(request, response);
}
}
浏览器中效果如下:
输入信息后:
3.总结
请求重定向的第一种方案:
// 设置响应状态码 302 ,表示重定向,(已搬迁)
resp.setStatus(302);
// 设置响应头,说明 新的地址在哪里
resp.setHeader("Location", "http://localhost:8080");
请求重定向的第二种方案(推荐使用):
resp.sendRedirect("http://localhost:8080");