King_Nanni King_Nanni - 1 month ago 13
HTML Question

Compare a database String value to an getParameter html value?

I have a local database, a login page and a servlet. I can get the values I want out of the database e.g. username and password. I can also get the user input in the html login form. I use request.getParameter for the html. I want to do a check if username from the database is equal to the username entered and if the password from the database is equal to the entered password access is granted else access denied. This is my CODE:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.Servlet;

import static com.sun.corba.se.spi.presentation.rmi.StubAdapter.request;
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import javax.servlet.RequestDispatcher;
import javax.sql.DataSource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author Jony
*/
public class LoginServlet extends HttpServlet {

private static Object request;

public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection connection = null;
Statement stmt = null;



try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
}
//STEP 3: Open a connection
System.out.println("Connecting to database...");
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/user_pass", "user", "pass");

//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = connection.createStatement();
String sql;
sql = "SELECT username, password FROM information";
ResultSet rs = stmt.executeQuery(sql);

while (rs.next()) {
//retrieve by column name
String usernamedb = rs.getString("username");
String passworddb = rs.getString("password");

if (usernamedb.equals(inputUsername) && passworddb.equals(inputPassword)) {
System.out.println("Login successful " + usernamedb + " " + passworddb);
} else {
System.out.println("Login failed " + usernamedb + " " + passworddb);
}

}

}

/**
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter out = response.getWriter();
String title = "Welcome";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType + title);

String inputUsername = request.getParameter("Name");
String inputPassword = request.getParameter("Pass");
}
}

Answer

I think you are just learning servlets. I also see you are a student at HvA, I am too and we are studying the same subject. Just continue the lessons and ask your teacher, this will all become clear. For now, this code will work the way you want:

package servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

/**
 * @author Jony
 */
public class LoginServlet extends HttpServlet {

    private static Object request;

    private boolean isValidUser(String username, String password) {
        Connection connection = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            //STEP 2: Register JDBC driver
            Class.forName("com.mysql.jdbc.Driver");

            //STEP 3: Open a connection
            System.out.println("Connecting to database...");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_pass", "user", "pass");

            //STEP 4: Execute a query
            System.out.println("Creating statement...");
            stmt = connection.createStatement();
            String sql = "SELECT username, password FROM information WHERE username='" + username + "' AND password = '" + password + "';";
            rs = stmt.executeQuery(sql);

            // Return true if a result is found.
            if (rs != null && rs.next()) {
                return true;
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        // Return false if no result is found or if there was an error.
        return false;
    }

    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        String title = "Welcome";
        String docType =
                "<!doctype html public \"-//w3c//dtd html 4.0 " +
                        "transitional//en\">\n";
        out.println(docType + title);

        String inputUsername = request.getParameter("username");
        String inputPassword = request.getParameter("password");

        // Check if user is valid.
        boolean validUser = isValidUser(inputUsername, inputPassword);

        // If user is valid, go to ...
        if (validUser) {
            System.out.println("Login successful");
        }// If user is not valid, do ...
        else {
            System.out.println("Login failed.");
        }

    }
}

Some things can be improved, like using prepared statements, but this will also be taught in future lessons. Happy coding!