2
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();
        }

    }

}

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

4

6 回答 6

4

您可以使用以下代码执行此操作,

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");

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

例如。

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();
于 2013-09-20T06:52:46.140 回答
0

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

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

所以类似于 [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");
        }
于 2013-09-20T06:50:52.657 回答
0

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

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

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

<form action ="one_servlet" >
<input type="text" name="username">
<input type="password" name="password"
<input type="submit" >
</form>
于 2013-09-20T06:54:03.487 回答
0

像这样的东西

 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();
        }

    }
于 2013-09-20T06:54:28.733 回答
0

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

阅读以下文章。

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://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) {

       }
于 2013-09-20T06:56:24.353 回答
0
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();
    }

  }

}

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

于 2013-09-20T07:44:30.193 回答