JAVA - > using JDBC and database connection pool learned before to realize a simple login function

This time, we use the jdbc we have learned before to write a simple login page (we will learn more about Ajax in the future)
The main comments are noted after the code! Read for yourself.

First look at the finished product page.

There are input user name, password, login button.
The pink area is the login status (login succeeded, login failed). Click login to change it according to the situation
The blue area is the clock, which is dynamic. It is realized by js cycle timer (setInterval()).

Database interface

(I'm too lazy to create a new table. I take an attack as a password.)

Login successfully

Landing failed

1. Page code

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <style>
    #time{
      width: 200px;
    }
    #jieguo{
      width: 200px;
    }
    #body{
      background-color: yellow;
      background-image: url("/img/u=146030364,2758798561&fm=26&gp=0.jpg");
      background-repeat: no-repeat;
      background-position: center;
    }
  </style>
  <script src="js/jquery.js"></script>
  <script src="js/index.js"></script>
  <body id="body">

<div id="all" align="center">
  <div>
    //User name:<input name="username" id="name">
  </div>
  <div>
    //dense&nbsp;&nbsp;&nbsp;&nbsp;Code:<input name="password" id="password">
  </div>
  <div>
    <button type="button" id="loginBtu">Sign in</button>
    <div id="jieguo" style="background-color: pink">Landing status</div>
  </div>
    <div id="time" align="center" style="background-color: aqua">time</div>
</div>

  </body>
</html>

2. File path

3.js file code (jQuery needs to be introduced), with a brief introduction to Ajax

$(function () {

   $("#loginBtu").click(function () {
   //Obtain the account password entered on the front page
       var name1 = document.getElementById("name").value;
       var password1 = document.getElementById("password").value;
   //Use Ajax! At present, understand first, and then focus on
       $.ajax(
           {
               url:"/login",     //Here is the URL of the jump = > @ webservlet (/ login)
               type:"get",
               data:{
                   name:name1,              //Pass the parameter name value to the background as name1 above
                   password:password1       //Pass the parameter password value to the background as password1 above
               },
               success:function (result) {       //If successful
              $("#jieguo").html(result);         //The div content with id jiegu will become result (the result returned in the background)
               }
           }
       )

   })

    // Dynamic time can be understood without much introduction
    function getTime() {
        var date = new Date();
        var h = date.getHours()<10?"0"+date.getHours().toString():date.getHours();
        var m = date.getMinutes()<10?"0"+date.getMinutes().toString():date.getMinutes();
        var s=date.getSeconds()<10?"0"+date.getSeconds().toString():date.getSeconds();
        var x=date.getDay();
        var xx;
        if(x==0){
            xx="Sunday";
        }
        else if(x==1){
            xx="Monday";
        }
        else if(x==2){
            xx="Tuesday";
        }
        else if(x==3){
            xx="Wednesday";
        }
        else if(x==4){
            xx="Thursday";
        }
        else if(x==5){
            xx="Friday";
        }
        else if(x==6){
            xx="Saturday";
        }
        var timeInfo = date.getFullYear()+"year"+(date.getMonth()+1)+"month"+date.getDate()+"day"+h+":"+m+":"+s+'</br>'+"---------"+'</br>'+xx;
        $("#time").html(timeInfo);
    }

    getTime();
    setInterval(getTime,1000)


});

4. Database connection pool code

Establishing c3p0 database configuration file

The name must be c3p0-config.xml or it will not be found automatically

<c3p0-config>
  <!-- Read connection pool objects using the default configuration -->
  <default-config>
  	<!--  Connection parameter -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/lol?characterEncoding=utf-8</property>
    <property name="user">root</property>
    <property name="password"></property>
    
    <!-- Connection pool parameters -->
    <property name="initialPoolSize">5</property>  //Number of initial connections
    <property name="maxPoolSize">10</property>  //maximum connection
    <property name="checkoutTimeout">3000</property>  //Connection delay
  </default-config>
 
</c3p0-config>

Create a tool class JDBC utils? C3p0

package login;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCUtils_c3p0 {

    private static DataSource dataSource;
    static {
         dataSource=new ComboPooledDataSource();       //Using the c3p0 database connection pool to automatically find the configuration file named c3p0-config.xml
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public static void getClose(Connection connection, Statement statement){
        try {
            if(connection!=null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(statement!=null){
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}


5. Log in the background Java code of Login

package login;


import druid.JDBCUtils;

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.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;

@WebServlet("/login")
public class Login extends HttpServlet  {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String name=req.getParameter("name");
        String password=req.getParameter("password");
        Connection connection = null;
        Statement statement=null;
        String a="Login failed";
        int i=0;
        try {
            connection = JDBCUtils.getConnection();
            statement=connection.createStatement();
            String sql="select * from hero where name='"+name+"'and attack='"+password+"'";
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next())
            {
                System.out.println(rs.getString(1) + "/t" +    rs.getString(2));
                i++;
            }
            if(i!=0){
                a="Login successfully";
            }
            resp.getWriter().write(a);    //Here is the result data returned to ajax in the background
            } catch (SQLException ex) {
            ex.printStackTrace();
        }finally {
             JDBCUtils_c3p0.getClose(connection,statement);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

At last, read my own writing and try to increase my proficiency in servlet and JDBC

63 original articles published, 41 praised, 10000 visitors+
Private letter follow

Tags: Java SQL JDBC Database

Posted on Thu, 13 Feb 2020 06:44:05 -0800 by rofl90