如果用户存在于数据库中则返回

时间:2014-02-09 12:57:10

标签: java mysql database jsp servlets

我有一个MySQL数据库,我有一个用户ID和密码列。他们每个人都有“mads”的价值。我有一些问题,我现在已经困难了几天,因为我没有编程这么长时间。我有一个JSP页面,我有我的表单和一个servlet,它连接到MySQL数据库。当我在用户ID和密码中输入mads时,我总是收到消息“你无效”。这意味着它可以给我答案“用户是有效的”,正如我想的那样。我不想创建用户,我只想检查用户是否存在于数据库中。我的JSP和servlet代码在这里:我希望有人可以帮助我,因为我真的不知道出了什么问题。

最诚挚的问候Mads

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Validation</title>
<style type="text/css">
/* border-radius er rundt hjørner på input..*/
input[type=text] {padding:5px; border:2px solid #ccc; webkit-border-radius: 5px; border-radius:5px;}
input[type=text]:focus{border-color:yellow;}
input[type=password] {padding:5px; border:2px solid #ccc; webkit-border-radius: 5px; border-radius:5px;}
input[type=password]:focus{border-color:yellow;}
input[type=submit] {padding: 5px 15px; background:#ccc; border:0 none; cursor:pointer; webkit-border-radius:5px; border-radius: 5px;}
</style>
</head>
<body>
    <br><br><br>
        <center>
            <h1>Please enter user name and password</h1>

            <form name="frm" action="LoginValidation" method="post">
                <input type="text" name="user">
                <input type ="password" name="pass">
                <input type="submit" value="Check" class="submit">
            </form>
        </center>
</body>

和我的Servlet:

import java.io.*;
//import java.util.*;
import java.sql.*;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.*;

@WebServlet(urlPatterns = {"/LoginValidation"})
public class Validation extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private ServletConfig config;

    public void init (ServletConfig config) 
    throws ServletException{
        this.config = config;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException,IOException {


        PrintWriter out = response.getWriter();
        String connectionURL = "jdbc:mysql://localhost/dblogin";
        Connection connection = null;
        ResultSet rs;
        String userid = request.getParameter("userid");
        String password =request.getParameter("password");
        ////and your select statement 

        try{
            String sql = "SELECT * FROM login WHERE userid = ? AND password = ?";
            Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "");

            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, userid);
            preparedStatement.setString(2, password);

             Statement s = connection.createStatement();
             rs =preparedStatement.executeQuery();

         ////if there are next ib rs so you have a user by this id and password 
             if(rs.next()) {
               out.println("The user is valid");
             }
             else {
               out.println("You are not valid");
             }

        }catch(Exception e) {
            System.out.println("The exception is" + e);
        }
    }
}

5 个答案:

答案 0 :(得分:1)

可能的解决方法:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
        PrintWriter out = response.getWriter();
        String connectionURL = "jdbc:mysql://localhost/dblogin";
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        String userid = request.getParameter("user");
        String password = request.getParameter("password");
        response.setContentType("text/html");

        try {
            // Load the database driver
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(connectionURL, "root", "");
            //Add the data into the database
            String sql = "SELECT * FROM login WHERE userid = ? AND password = ?";

            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, userid);
            preparedStatement.setString(2, password);

            rs = preparedStatement.getResultSet();

            if(rs.next()) {
                // redirect or print but not both...
                out.println("The user is valid");
                // response.sendRedirect("index_true.jsp");
            } else {
                out.println("You are not valid");
            }
        } catch(Exception e) {
            System.out.println("Exception is: " + e);
        } finally {
            // TODO: check for nullity
            rs.close();
            preparedStatement.close();
            connection.close();
        }
    }

修正:

  • 使用request参数从DB中获取记录
  • 执行正确的陈述
  • ...

(可能仍有一些问题,未经测试)

答案 1 :(得分:0)

useridpassword有一个空字符串,您可以使用此值进行查询,因此不返回任何内容

因此您首先需要从用户那里获取useridpassword,然后使用此值进行查询,如果有结果,那么您就拥有有效的用户

String userid = request.getParameter("userid");
String password =request.getParameter("password");
////and your select statment 
String sql = "SELECT * FROM login WHERE userid = ? AND password = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, userid);
preparedStatement.setString(2, password);

 Statement s = connection.createStatement();
 rs =preparedStatement.executeQuery();

////if there are next ib rs so you have a user by this id and password 
if(rs.next()) {
  out.println("The user is valid");
}
else {
  out.println("You are not valid");
}

答案 2 :(得分:0)

在表单中,参数名称是user,但在servlet中使用的是getParameter(“UserId”)

在这种情况下,调试servlet代码以检查接收的参数可能很有用。

还要考虑先前对正确选择语法的评论,并且您传递的空字符串是查询参数,您应该使用请求参数并删除结果检查,因为它与查询本身重复。

答案 3 :(得分:0)

您的查询未返回任何结果。您需要做的是将userId和password设置为通过post post发送的值。

 userid = request.getParameter("userid");
 password = request.getParameter("password");

当您运行查询时,如果您的用户名是唯一的(它们应该是),则不需要循环。

答案 4 :(得分:0)

这是正确答案:

&lt;%@ page language =“java”contentType =“text / html; charset = US-ASCII”         的pageEncoding = “US-ASCII” %&GT;                         验证          / * border-radius errundthjørnerpåinput.. * /     输入[type = text] {padding:5px; border:2px solid #ccc; webkit-border-radius:5px;边界半径:5像素;}     输入[类型=文本]:焦点{边框颜色:黄色;}     输入[type =密码] {填充:5px; border:2px solid #ccc; webkit-border-radius:5px;边界半径:5像素;}     输入[类型=密码]:焦点{边框颜色:黄色;}     输入[type = submit] {padding:5px 15px;背景:#CCC;边界:0无;光标:指针; WebKit的边界半径:5像素; border-radius:5px;}                        


                             

请输入用户名和密码

            <form name="frm" action="LoginValidation" method="post">
                <input type="text" name="userid">
                <input type ="password" name="password">
                <input type="submit" value="Check" class="submit">
            </form>
        </center>
</body>

package jsp;

import java.io.*;
import java.sql.*;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.*;

@WebServlet(urlPatterns = {"/LoginValidation"})
public class Validation extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException,IOException {

        PrintWriter out = response.getWriter();
        String connectionURL = "jdbc:mysql://localhost/dblogin";
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        String userid = request.getParameter("userid");
        String password =request.getParameter("password");
        response.setContentType("text/html");


        try{
            Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "");
            String sql = "SELECT * FROM login WHERE userid = ? AND password = ?";

            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, userid);
            preparedStatement.setString(2, password);

             //Statement s = connection.createStatement();
             rs =preparedStatement.executeQuery();

             if(rs.next()) {
               out.println("The user is valid");
             }
             else {
               out.println("You are not valid");
             }

        }catch(Exception e) {
            System.out.println("The exception is" + e);

        }

    }
}