Request 获取根据页面获取用户输入判断登陆成功或者失败

时间:2021-01-12
本文章向大家介绍Request 获取根据页面获取用户输入判断登陆成功或者失败,主要包括Request 获取根据页面获取用户输入判断登陆成功或者失败使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/validateUser")      //注意加/
public class ValidateUser extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] usernames = {"小孙", "小王", "小刘"};
        String[] passwords = {"000000", "111111", "222222"};
        //接收客户端的表单数据
        req.setCharacterEncoding("utf-8");
        //用户名 和 密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //判断
        for (int i = 0; i < usernames.length; i++) {
            if (usernames[i].equals(username)) {
                //再次判断密码是否相同
                if (passwords[i].equals(password)) {
                    //跳转到成功页面
                    req.getRequestDispatcher("/登陆成功.html").forward(req, resp);
                    return;//结束
                }
            }
        }
        req.getRequestDispatcher("/登陆失败.html").forward(req, resp);
    }
}

登陆页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--<a href="/admin.html">这是爆炸信息!嘿嘿嘿</a>
<form action="/login" method="get">
    <input type="text" placeholder="用户名" name="username">
    <input type="password" placeholder="密码" name="password">
    <input type="submit" value="登陆">
</form>-->


<form action="/day48/validateUser" method="get">
    <input type="text" placeholder="用户名" name="username">
    <input type="password" placeholder="密码" name="password">
    <input type="submit" value="校验">
</form>

</body>
</html>

登陆成功.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>登陆成功</h2>
</body>
</html>

登陆失败.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>登陆失败</h2>
</body>
</html>