Java web simple registration and landing project case

core technology

  • java web servlet: HttpServlet class, configuration of Servlet class based on @WebServlet() comment
  • tomcat project deployment
  • mysql database
  • jdbc
  • druid database connection pool
  • html

Software used

  • java web integrated development environment: IntelliJ IDEA
  • Server: tomcat
  • Visualization interface for mysql: SQLyog

jar packages used

  • The jar packages required for the project: druid-1.0.9.jar, mysql-connector-java-5.1.48-bin.jar
  • druid-1.0.9.jar: Druid database connection pool driver package for Alibaba
  • mysql-connector-java-5.1.48-bin.jar: driver package for database connection of jdbc

Case Requirements

  • A simple web project that enables login operations with specified account passwords and displays login results
  • Implement registration and login functions
  • Store registered accounts in mysql database
  • Using druid database connection pool technology

Configuration of project jar packages and databases

  • The jar package for a web project is first placed in the WEB-INF directory under the web directory
  • Right-click the libs folder to select Add as Library
  • Add the two jar packages in tomcat's lib directory (otherwise the web project will not find the class when the browser runs)
  • The configuration file druid.properties for the database connection pool Druid is placed in the src folder
  • Configuration information for druid.properties
    # Driver directory for jdbc,class.forName();
    driverClassName=com.mysql.jdbc.Driver
    # url of database
    url=jdbc:mysql://127.0.0.1:3306/city
    # Account to connect to
    username=root
    # Password for the account to be linked 
    password=root
    # Number of connection objects in the initial connection pool
    initialSize=5
    # Maximum number of connection objects
    maxActive=10
    # Maximum Wait Time
    maxWait=3000
    
  • Create users table in mysql database
    CREATE TABLE users (
    USER VARCHAR(30) UNIQUE NOT NULL,
    PASSWORD VARCHAR(50) NOT NULL
    );
    

Writing druid tool classes

  • Requirements: Implement the Get Connection Object method, implement the close method of PreparedStatement,ResultSet,Connection Object
  • DruidUtils class code
    package cn.web.jdbc;
    
    
    import com.alibaba.druid.pool.DruidDataSourceFactory;
    
    import javax.sql.DataSource;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Properties;
    
    public class DruidUtils {
    
        private static DataSource dataSource;
    
        static {
            Properties properties = new Properties();
            ClassLoader classLoader = DruidUtils.class.getClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream("druid.properties");
            try {
                properties.load(inputStream);
                dataSource = DruidDataSourceFactory.createDataSource(properties);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static DataSource getDataSource() {
            return dataSource;
        }
    
        public static Connection getConnection() {
            try {
                return dataSource.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return null;
        }
    
        public static void close(PreparedStatement preparedStatement) {
            if(preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static void close(Connection connection) {
            if(connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static void close(ResultSet resultSet) {
            if(resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static void close(PreparedStatement preparedStatement, Connection connection, ResultSet resultSet) {
            close(preparedStatement);
            close(resultSet);
            close(connection);
        }
    
        public static void close(PreparedStatement preparedStatement, Connection connection) {
            close(preparedStatement);
            close(connection);
        }
    }
    
    

Write UserManager classes (manage user objects)

  • Requirements: Enable registration and login functions
  • UserManager class code
    package cn.web.user;
    
    import cn.web.jdbc.DruidUtils;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public class UserManager {
    
        private static String REGISTER_SQL = "INSERT INTO users VALUES (?, ?)";
        private static String LOGIN_SQL = "SELECT * FROM users WHERE user = ? AND password = ?";
    
        private static Connection connection;
        private static PreparedStatement preparedStatement;
        private static ResultSet resultSet;
    
        private static void getConnection() {
            connection = DruidUtils.getConnection();
        }
    
        private static void getPreparedStatement(String sql) {
            try {
                preparedStatement = connection.prepareStatement(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
        private static void setPreparedStatement(String user, String password) {
            try {
                preparedStatement.setString(1, user);
                preparedStatement.setString(2,password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
        public static boolean login(String user, String password) {
            boolean count = true;
            getConnection();
            getPreparedStatement(LOGIN_SQL);
            setPreparedStatement(user, password);
    
            try {
                resultSet = preparedStatement.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    
            try {
                if(!resultSet.next()) {
                    count = false;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
    
            DruidUtils.close(preparedStatement, connection, resultSet);
    
            return count;
        }
    
    
        public static boolean register(String user, String password) {
            int count = -1;
            getConnection();
            getPreparedStatement(REGISTER_SQL);
            setPreparedStatement(user, password);
    
            try {
                count = preparedStatement.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    
            DruidUtils.close(preparedStatement, connection, resultSet);
            return count == 1 ? true : false;
        }
    }
    

A servlet class that implements registration and login

  • Requirements: Return results for registration and login
  • LoginServlet class code implementation
    package cn.web.net;
    
    import cn.web.user.UserManager;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @WebServlet(urlPatterns = {"/login"})
    public class LoginServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html; charset=utf-8");
            boolean result = UserManager.login(request.getParameter("user"), request.getParameter("password"));
            if(result) {
                response.getWriter().write("Landing Success!");
            } else {
                response.getWriter().write("Logon Failure!");
            }
        }
    }
    
    
  • Code implementation of RegisterServlet class
    package cn.web.net;
    
    import cn.web.jdbc.DruidUtils;
    import cn.web.user.UserManager;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    @WebServlet(urlPatterns = {"/register"})
    public class RegisterServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html; charset=utf-8");
            boolean result = UserManager.register(request.getParameter("user"), request.getParameter("password"));
            if(result == true) {
                response.getWriter().write("login was successful!");
            } else {
                response.getWriter().write("login has failed!");
            }
        }
    }
    
    

Write html files for landing and registration pages

Registration Page

  • register.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>register</title>
    </head>
    <body>
    developer:tom<br>
    <form action="/register" method="post">
        <input type="text" placeholder="user" name="user"><br>
        <input type="text" placeholder="password" name="password"><br>
        <input type="submit" name="register">
    </form>
    </body>
    </html>
    
  • Page Effects

Landing Page

  • login.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Land</title>
    </head>
    <body>
    <form action="/login" method="post">
        <input type="text" placeholder="user" name="user"><br>
        <input type="text" placeholder="password" name="password"><br>
        <input type="submit" value="Land">
    </form>
    </body>
    </html>
    
  • Page Effects

Deployment of the project


Points stepped on in this project

  • The lib file for the jar package is placed under web/WEB-INF
  • The jar package should also be placed in the lib folder of tomcat
  • Try not to have Chinese names for project paths. If there are Chinese names, use the java.net.URLDecoder.decode() method to re-encode them.
  • The page uses the response.getWriter().write() method to scramble Chinese and response.setContentType("text/html; charset=utf-8") to set the encoding.

Project Source Download

  • Link: https://pan.baidu.com/s/1nkdKUhrGlptmMBkcVKHbzw
  • Extraction Code: n1p1
76 original articles published, 18 praised, 2664 visited
Private letter follow

Keywords: Java SQL Druid MySQL

Added by tolli on Tue, 28 Jan 2020 04:11:37 +0200