Java 如何从数据库编写查询登录页面 servlet

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18910439/
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-08-12 12:14:40  来源:igfitidea点击:

how to write Query Login page servlet from data base

javamysqljspservlets

提问by user2794306

package java4s;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OnServletLogin extends HttpServlet {

    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS";
    static final String USER = "root";
    static final String PASS = "";

    protected void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Database..");
            stmt = conn.createStatement();
            String sql = "SELECT id, userId, password FROM login";
            ResultSet rs = stmt.executeQuery(sql);


            PrintWriter pw = res.getWriter();
            res.setContentType("text/html");

            String user = req.getParameter("userName");
            String pass = req.getParameter("userPassword");

            pw.print("<font face='verdana'>");

            if (user.equals("select * from login where userId="+user+"and password"+pass) )
                pw.println("Login Success...!");
            else
                pw.println("Login Failed...!");

            pw.print("</font>");
            pw.close();

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

Hi this is my code, I am trying to implement a login page from database, but I am unable to put the logic for login from database data. I create table loginin that I have 2 fields user idand password.But how to retrieve and how fetch so that I can enable login?

嗨,这是我的代码,我正在尝试从数据库实现登录页面,但我无法从数据库数据中放置登录逻辑。我创建的表login中有 2 个字段user idpassword.但是如何检索以及如何获取以便我可以启用登录?

采纳答案by Ajeesh

You can do this by using the below code,

你可以使用下面的代码来做到这一点,

String user = req.getParameter("userName");
  String pass = req.getParameter("userPassword");
  String id=null;
  String userId=null;

  String sql = "SELECT id, userId, password FROM login where username='"+user+"' and password='"+pass+"'";
        ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
 {
 id=rs.getString("id");
userId=rs.getString("userId");   
}

if(id!=null)
System.out.println("Login Success");
else
System.out.println("Login Failed");

UPDATE:Try using prepared statement instead of directly passing values to sql query.

更新:尝试使用准备好的语句而不是直接将值传递给 sql 查询。

Eg.

例如。

PreparedStatement pst = null;
String sql = "SELECT id, userId, password FROM login where username=? and password=?";
pst = con.prepareStatement(sql);
pst.setString(1,user);
pst.setString(2,pass);
ResultSet rs = pst.executeQuery();

回答by bezzoon

select * from TABLE where userid=blah AND password=blah

select * from TABLE where userid=blah AND password=blah

if exactly one matching row exists then go ahead with it and let the dude log in by setting session variables that would otherwise redirect the user from other pages and stuff.

如果恰好存在一个匹配的行,则继续使用它并让花花公子通过设置会话变量登录,否则这些变量会将用户从其他页面和内容重定向。

So something along the lines of [This example on has a username, no password]

所以类似于[这个例子有一个用户名,没有密码]

        String user = request.getParameter("username");

        String sqlStr = "select * FROM customers WHERE name = " + "\"" + user
                + "\"";

        out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for //
                                                            // debugging
        ResultSet rset = stmt.executeQuery(sqlStr); // Send the query to the
                                                    // // server
        boolean hasResult = rset.next();
        if (hasResult) {
            out.println("Logged in!");
            HttpSession session = request.getSession(true);
            session.setAttribute("USER", user);
            String role = rset.getString("role");

            if (role.equals("owner")) {
                response.sendRedirect("categories.jsp");
            } else {
                response.sendRedirect("productsbrowsing.jsp");
            }
        } else {
            out.println("User not found");
        }

回答by SpringLearner

In the login page,create a form that accepts username and password.This form should call a servlet where you need to get the entered username and password using this way

在登录页面中,创建一个接受用户名和密码的表单。这个表单应该调用一个servlet,您需要使用这种方式获取输入的用户名和密码

request.getParameter("username");
request.getParameter("password");

Then get the original username and password from the database.Match with this one.If matches then create a session and forward to next page else send to login page

然后从数据库中获取原始用户名和密码。与这个匹配。如果匹配,则创建一个会话并转发到下一页,否则发送到登录页面

<form action ="one_servlet" >
<input type="text" name="username">
<input type="password" name="password"
<input type="submit" >
</form>

回答by Suresh Atta

Something like this

像这样的东西

 try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        System.out.println("Database..");
        stmt = conn.createStatement();
        String db_username = null;
        String db_password = null;
            query = "SELECT username, password FROM login;";
            stmt.executeQuery(query);
            ResultSet rs = stmt.getResultSet();

            while(rs.next()){
                db_username = rs.getString("username");
                db_password = rs.getString("password");
                //check null's also 
                if(dbUsername.equals(username) && dbPassword.equals(password)){
                   System.out.println("sucess");

                }

            }
        }  catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

回答by Prabhakaran Ramaswamy

Please use PreparedStatemen to Fix SQL Injection......

请使用 PreparedStatemen 修复 SQL 注入......

Read the below artices.

阅读以下文章。

http://www.javacodegeeks.com/2012/11/sql-injection-in-java-application.html

http://www.javacodegeeks.com/2012/11/sql-injection-in-java-application.html

http://software-security.sans.org/developer-how-to/fix-sql-injection-in-java-using-prepared-callable-statement

http://software-security.sans.org/developer-how-to/fix-sql-injection-in-java-using-prepared-callable-statement

http://en.wikipedia.org/wiki/SQL_injection

http://en.wikipedia.org/wiki/SQL_injection

      try {
            String user = req.getParameter("userName");
            String pass = req.getParameter("userPassword");
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Database..");
            PreparedStatement stmt = conn.prepareStatement("SELECT id, userId, password FROM login WHERE userId=? AND password=?");
            stmt.setString(1, user);
            stmt.setString(2, pass);
            ResultSet rs = stmt.executeQuery();

            PrintWriter pw = res.getWriter();
            res.setContentType("text/html");        

            pw.print("<font face='verdana'>");

           if (rs.next() ) {
                pw.println("Login Success...!");
            else
                pw.println("Login Failed...!");

            pw.print("</font>");
            pw.close();

        } catch (ClassNotFoundException e) {

       }

回答by viveksyngh

package java4s;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OnServletLogin extends HttpServlet {

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS";
static final String USER = "root";
static final String PASS = "";

protected void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    Connection conn = null;
    Statement stmt = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        System.out.println("Database..");
        PreparedStatement ps=con.prepareStatement("select * from login where userid=? and password=?"); 



        PrintWriter pw = res.getWriter();
        res.setContentType("text/html");

        String user = req.getParameter("userName");
        String pass = req.getParameter("userPassword");
        ps.setString(1,user);
        ps.setString(2,pass);
        ResultSet rs=ps.executeQuery();

        pw.print("<font face='verdana'>");

        if(rs.next())
          pw.println("Login Success...!");
        else
          pw.println("Login Failed...!");



        pw.print("</font>");
        pw.close();

    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

  }

}

}

try this one , i have edited your code

试试这个,我已经编辑了你的代码