Search code examples
javamysqldatabasejspservlets

return if a user exist in database


I have a MySQL database where I have a userid and a password column. Each of them has the value "mads". I have some problems that I have been struggling with some days now, because I didn't program so long time. I have a JSP page where I have my form and a servlet who makes the connection to the MySQL database. When i put in mads in userid and password I get always the message "You are not valid". That means it dosent give me the answer "The user is valid", as I would like to. I would not like to create a user, I would just like to check if the user exist in the database. My JSP and servlet code is here: I hope somebody can help me, because I really don't know what is wrong.

Best Regards 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>

And My 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);
        }
    }
}

Solution

  • Probable fix:

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

    Fixed:

    • use request parameter to fetch a record from the DB
    • execute the proper statement
    • ...

    (there might still be some issues, this was not tested)