Compare a database string value to a html getParameter value?

综合技术 2018-03-13

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 =
      "n";
      out.println(docType + title);

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

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 =
                "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!

您可能感兴趣的

4 Improvements to Azure SQL Database If I was a wizard I would make these 4 improvements to Azure SQL Database. They are in no particular order, in fact I could come up with about 10 feat...
当Java遇见了Html–Jsp九大内置对象篇... jsp内置对象对象是web容器创建的一组对象,不使用new关键词久可以使用的内置对象。 九大内置对象包括以下: out –JspWriter request –ServletRequest reponse –ServletResponse ...
新学说发布国际学校在线四库全书,开启行业全方位数据支持时代... 芥末堆 10月26日讯 今日,国际学校服务平台新学说在北京举办发布会,宣布“国际学校在线四库全书”正式上线。“国际学校在线四库全书”是由“国际学校库”、“国际教育机构库”、“国际教育人才库”、“国际学校行业项目库”组成。 “国际学校在线四库全书”页面 国际学校库收录了全国940...
YugaByte’s new database software rakes in $16 mill... Looking to expand the footprint of its toolkit giving developers a unified database software that can work for both relational and post-relational dat...
Vulnerability Databases: Classification and Regist... What publicly available Vulnerability Databases do we have? Well, I can only say that there are a lot of them and they are pretty different. Here I...
0
Hello, buddy!

责编内容来自:Hello, buddy! (本文源链)
阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。