java 我想使用 servlet 创建一个登录页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3423306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:46:48  来源:igfitidea点击:

I want to create a login page using servlets

javamysqljspservletsjdbc

提问by Vin

I want to create a login page using Servlet & JSP.

我想使用 Servlet 和 JSP 创建一个登录页面。

I ve created a page which gets Username & password.

我创建了一个获取用户名和密码的页面。

I made a database with a table which contains Username & password.

我用一个包含用户名和密码的表创建了一个数据库。

<form action="LoginPage" method="POST">
    User name: <input type="text" name="userName" size="20"><br>
    Password: <input type="password" name="password" size="20">
    <br><br>
    <input type="submit" value="Submit">
</form> 

I entered the below code in doPost()

我在 doPost() 中输入了以下代码

 response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String userName = request.getParameter("userName").toString();
    String passWord = request.getParameter("password").toString();
    Connection con = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "userdb";
    String driver = "com.mysql.jdbc.Driver";
    String user = "root"; 
    String password = "1234";
    try {
        Class.forName(driver).newInstance();
        Connection conn = DriverManager.getConnection(url+dbName, user, password);
        PreparedStatement pstmt;
        String sql = "SELECT USR_NAME FROM LOGIN WHERE USR_NAME='userName'";
        pstmt = conn.prepareStatement(sql);
        ResultSet rs=pstmt.executeQuery();
        String usr = null;
        String pass = null;
        while(rs.next())
        {
            pass = rs.getString(3);
        }
        if(pass != null && pass.equals(passWord))
        {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Login Sucessfull</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Login Sucessfull " + request.getContextPath () + "</h1>");
            out.println("<p>Welcome</p> " + userName);
            out.println("</body>");
            out.println("</html>");

            out.close();
        }

    } catch (Exception e) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Login is not Sucessfull</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Login is not Sucessfull " + request.getContextPath () + "</h1>");
        out.println("<p>Wrong Username Or Password</p> ");
        out.println("</body>");
        out.println("</html>");

        out.close();

And I dont know how to make it work. Any Quick Fix Available For me?

我不知道如何使它工作。有什么可用的快速修复方法吗?

Its not a big project, i jus want a Login page which gets username & password then the servlet will search the username in DB then checks for password. I have made the changes you guys told. But the output looks like something wrong in try block, Because, I get the Login not successful page. I put the code "Login not successful Page" in Catch block.

它不是一个大项目,我只是想要一个登录页面,它获取用户名和密码,然后 servlet 将在数据库中搜索用户名,然后检查密码。我已经做了你们所说的改变。但是输出在 try 块中看起来有问题,因为,我得到了登录不成功页面。我将代码“登录不成功页面”放在 Catch 块中。

回答by BalusC

It's unclear what you mean with "How to make it work". What happens? What happens not? At least I can spot several problems in your code:

目前尚不清楚“如何使其工作”的含义。怎么了?不会发生什么?至少我可以在你的代码中发现几个问题:

  1. You are emitting HTML inside a servlet. You should use JSP for this.
  2. You are leaking JDBC resources. You need to close them in finally.
  3. You are not setting the enteredusername (and password) in the SQL string.
  4. You are not letting the DB do the task of comparing the password. Add it to the WHERE.
  5. You are swallowing the exception. All detailed info about the problem cause get lost. You should either rethrow it as ServletExceptionor at least log the exception type, message and cause. This information is important since it tells something about the root cause of the problem. You know, once the root cause is understood, the solution is obvious.
  1. 您正在 servlet 内发出 HTML。为此,您应该使用 JSP。
  2. 您正在泄漏 JDBC 资源。您需要将它们关闭在finally.
  3. 您没有在 SQL 字符串中设置输入的用户名(和密码)。
  4. 您不会让数据库执行比较密码的任务。将其添加到WHERE.
  5. 你正在吞下异常。有关问题原因的所有详细信息都会丢失。您应该将其重新抛出ServletException或至少记录异常类型、消息和原因。此信息很重要,因为它可以说明问题的根本原因。您知道,一旦了解了根本原因,解决方案就显而易见了

Further it's also bad user experience if you change the page to a page where the user can do absolutely nothing else than facing an error message. The user has to take extra handling to go back to the login page to re-enter the details. Rather redisplay the same page with the error message inlined.

此外,如果您将页面更改为用户除了面对错误消息之外什么也做不了的页面,这也是糟糕的用户体验。用户必须进行额外的处理才能返回登录页面以重新输入详细信息。而是重新显示内联错误消息的同一页面。

Rewrite your doPost()method as follows:

重写你的doPost()方法如下:

String userName = request.getParameter("userName");
String passWord = request.getParameter("password");

String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "userdb";
String user = "root"; 
String password = "1234";
String sql = "SELECT * FROM LOGIN WHERE USR_NAME = ? AND USR_PASS = ?"; // Not sure how the password column is named, you need to check/update it. You should leave those ? there! Those are preparedstatement placeholders.

Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean login = false;

try {
    Class.forName(driver); // You don't need to call it EVERYTIME btw. Once during application's startup is more than enough.
    connection = DriverManager.getConnection(url + dbName, user, password);
    statement = connection.prepareStatement(sql);
    statement.setString(1, userName);
    statement.setString(2, password);
    resultSet = statement.executeQuery();
    login = resultSet.next();
} catch (Exception e) {
    throw new ServletException("Login failed", e);
} finally {
    if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
    if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
    if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}

if (login) {
    request.getSession().setAttribute("username", userName); // I'd prefer the User object, which you get from DAO, but ala.
    response.sendRedirect("home.jsp"); // Redirect to home page.
} else {
    request.setAttribute("message", "Unknown username/password, try again"); // This sets the ${message}
    request.getRequestDispatcher("login.jsp").forward(request, response); // Redisplay JSP.
}

And add ${message}to your JSP:

并添加${message}到您的 JSP:

<form action="LoginPage" method="POST">
    User name: <input type="text" name="userName" size="20"><br>
    Password: <input type="password" name="password" size="20">
    <br><br>
    <input type="submit" value="Submit"> ${message}
</form>

Here are some links to learn how to do JSP/Servlet/JDBC properly.

这里有一些链接可以学习如何正确地执行 JSP/Servlet/JDBC。

回答by Vin

you should use SELECT PASSWORD from Loginin the sql query here PASSWORDis the column name which contains password in your database table LOGIN

您应该SELECT PASSWORD from Login在此处的 sql 查询中使用PASSWORD包含数据库表中密码的列名LOGIN

回答by vcosk

toString() for request.getParameter is not required.

request.getParameter 的 toString() 不是必需的。

You can modify your query to

您可以将查询修改为

String sql = "SELECT <PASSWORD_CLM> FROM LOGIN WHERE USR_NAME="+userName;


while(rs.next()) 
{ 
   //read the password in pass. 
} 
if(pass !=null && pass.equals(passWord)) 
{ 
  // Code
}

回答by Dean

I am seeing problems with the lines:

我看到线路有问题:

  String sql = "SELECT USR_NAME FROM LOGIN WHERE USR_NAME='userName'";
    pstmt = conn.prepareStatement(sql);
    ResultSet rs=pstmt.executeQuery();
    String usr = null;
    String pass = null;

It should be:

它应该是:

String sql = "SELECT * from LOGIN WHERE USR_NAME="+ userName+";";

Also check the table name for the login information as you have it as LOGINsure it isn't login? Also i would avoid writing HTML in the servlet and just let it forward to another JSP. It could just be something simple for now. Saying Logged in. Dean

还要检查登录信息的表名,因为您LOGIN确定它不是login吗?此外,我会避免在 servlet 中编写 HTML,而只是让它转发到另一个 JSP。现在可能只是一些简单的事情。说已登录。Dean