简体   繁体   English

我想使用Servlet创建登录页面

[英]I want to create a login page using servlets

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. 它不是一个大项目,我想获得一个获取用户名和密码的登录页面,然后servlet将在数据库中搜索用户名,然后检查密码。 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. 但是输出在try块中看起来好像有问题,因为,我得到了Login not success页面。 I put the code "Login not successful Page" in Catch block. 我在Catch块中输入了代码“ Login not success Page”。

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. 您正在servlet中发出HTML。 You should use JSP for this. 您应该为此使用JSP。
  2. You are leaking JDBC resources. 您正在泄漏JDBC资源。 You need to close them in finally . 您需要finally将它们关闭。
  3. You are not setting the entered username (and password) in the SQL string. 您没有在SQL字符串中设置输入的用户名(和密码)。
  4. You are not letting the DB do the task of comparing the password. 您不让数据库执行比较密码的任务。 Add it to the WHERE . 将其添加到WHERE
  5. You are swallowing the exception. 您正在吞下例外。 All detailed info about the problem cause get lost. 有关问题原因的所有详细信息都将丢失。 You should either rethrow it as ServletException or at least log the exception type, message and cause. 您应该将其作为ServletException重新抛出,或者至少记录异常类型,消息和原因。 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 . 您知道,一旦了解了根本原因,解决方案就显而易见了

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。

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
}

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

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 LOGIN sure it isn't login ? 还在为登录信息查询表名,你把它当作LOGIN确定没有login Also i would avoid writing HTML in the servlet and just let it forward to another JSP. 另外,我将避免在servlet中编写HTML,而只是将其转发给另一个JSP。 It could just be something simple for now. 现在可能只是简单的事情。 Saying Logged in. Dean 说登录。Dean

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM