A detailed jsp+servlet+jdbc+mysql check login operation (IntelliJ IDEA)

Step 1: first, create a table in the database:

This table is the user information table used for login.

Step 2: do a good job of the front-end login jsp page:


The code is as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Sign in</title>
</head>
<body>
    <form action="LoginServlet" method="post">
        Account number:<input name="username" type="text"/><br>
        Password:<input name="password" type="text"/><br>
        <input value="Sign in" type="submit"/><br>
    </form>

</body>
</html>

Step 3: integrate JDBC environment

3.1 the driver of importing mysql is added to the module.

3.1.1 copy and paste the downloaded mysql driver into web/WEB-INF/lib.

3.1.2 open project Structure(Ctrl + Alt + Shift +s), click Modules on the left, select the Modules you want to add, click the + button on the right to find the jar package of mysql, and click ok to finish.


3.2 create jdbc.properties and store it under src.

driverclass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost/stuproject
name=root
password=123456

3.3 create the tool class JDBCUtils.java for getting connection and closing database connection resources, where all methods are static methods

public class JDBCUtils {

    static String driverclass = null;
    static String url = null;
    static String name = null;
    static String password = null;

    static{
        try {
            Properties pros = new Properties();
            // Using classLoader to get resources under src
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            pros.load(is);//Read input stream

            //read attribute
            driverclass = pros.getProperty("driverclass");
            url = pros.getProperty("url");
            name = pros.getProperty("name");
            password = pros.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  Get database connection
     * @return
     */

    public static Connection getConn(){

        Connection conn = null;
        try {
            //1. Register driverclass with reflection
            Class.forName(driverclass);
            //2. Establish connection parameter 1: Protocol + ACCESS database, parameter 2: user name, parameter 3: password.
            conn = DriverManager.getConnection(url, name, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     *  Close connection resources
     * @param conn
     */
    public static void release(Connection conn,PreparedStatement ps){
        closeConn(conn);
        closePs(ps);
    }
    public static void release(Connection conn,PreparedStatement ps,ResultSet rs){
        closePs(ps);
        closeConn(conn);
        closeRs(rs);
    }


    public static void closeConn(Connection conn){
        try {
            if(conn != null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            conn = null;
        }
    }

    public static void closePs(PreparedStatement ps){
        try {
            if(ps !=null){
                ps.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ps=null;
        }
    }
    public static void closeRs(ResultSet rs){
        try {
            if(rs !=null){
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            rs=null;
        }
    }

}

Step 4: set up DAO and DaoImpl (the method to implement the verification login) for processing business logic.

4.1 UserDao interface

The interface defines a set of standards without specific implementation.

public interface UserDao {
    /**
     *  Verify login method
     */
    boolean login(String username,String password);
}

4.2 UserDaoImpl implementation class

This class implements the UserDao interface, which is used to complete the method of verifying login.

public class UserDaoImpl implements UserDao {
    /**
     *  Method used to verify login
     * @param username
     * @param password
     * @return
     */
    @Override
    public boolean login(String username, String password) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            //1. Get database connection
            conn = JDBCUtils.getConn();
            //2. Precompile sql statements
            String sql = "select * from t_user where username=? and password=?";
            ps = conn.prepareStatement(sql);
            //3. Fill placeholder
            ps.setString(1,username);
            ps.setString(2,password);

            //4. Execute query statement
            rs = ps.executeQuery();
            //5. If there are objects in the result set, it will return true if found. If not. Then return false
            return rs.next();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //6. Close resources
            JDBCUtils.release(conn,ps,rs);
        }

        return false;
    }
}

Step 5: complete LoginServlet.java for jump

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");//Set character set of request
        response.setContentType("text/html;charset=utf-8");//Set character set of response

        //1. Get the username and password values from the front page
        String userName = request.getParameter("username");
        String passWord = request.getParameter("password");

        //2. Create the object of the implementation class and call the login() method
        //If the database is found, it will return true; if it is not found, it will return false
        UserDaoImpl userDao = new UserDaoImpl();
        boolean isSuccess = userDao.login(userName, passWord);

        if(isSuccess){
            //Used for corresponding customer, success is true -- > login succeeded
            response.getWriter().write("Login successfully");
        }else{
            response.getWriter().write("Login failed");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

Finally, run login.jsp, enter the username and password in the database, and log in successfully

The following is the project directory:

Published 3 original articles, won praise 0, visited 14
Private letter follow

Tags: Database JDBC MySQL Java

Posted on Sat, 14 Mar 2020 12:12:12 -0400 by Tremor