public void sendRedirect(java.lang.String location) throws java.io.IOException
在上述方法代码中,参数 location 可以使用相对 URL,Web 服务器会自动将相对 URL 翻译成绝对 URL,再生成 Location 头字段。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<!-- 把表单内容提交到 servletDemo02 工程下的 LoginServlet -->
<form action="/servletDemo02/LoginServlet" method="POST">
用户名:<input type="text" name="username"><br/>
密 码:<input type="password" name="password"/><br/>
<br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>欢迎页面</title>
</head>
<body>
欢迎你,登陆成功!
</body>
</html>
package com.mengma.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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");
// 假设用户名和密码分别为 admin 和 123456
if ("admin".equals(username) && ("123456").equals(password)) {
// 如果用户名和密码正确,重定向到 welcome.html
response.sendRedirect("/servletDemo02/welcome.html");
} else {
// 如果用户名和密码错误,重定向到 login.html
response.sendRedirect("/servletDemo02/login.html");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
doGet(request, response);
}
}
在上述代码中,首先通过 getParameter() 方法分别获取用户名和密码,然后判断表单中输入的用户名和密码是否为指定的“admin”和“123456”,如果是,则将请求重定向到 welcome.html 页面,否则重定向到 login.html 页面。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有