实现用户注册和登录系统

     目录

项目结构

                  一、架包的运用

                  二、工具包

DBlink

IRowMapper(接口)

MD5Tool(加密)

PropertiesTool

                  三、Main包


项目结构

实现用户注册和登录系统_第1张图片

一、架包的运用

用于异常处理的架包  log4j-1.2.15.jar

用于连接数据库的架包  mysql-connector-java-5.1.44-bin.jar

复制粘贴后 右键—Build path—add

并创建File  db.properties  和   log4j-1.2.15.jar

//db.properties
db.username=root;
db.password=root;
db.url=jdbc:mysql://127.0.0.1:3306/test

二、工具包

DBlink

package com.jd.Tool.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

import com.jd.Tool.PropertiesTool;

/**
 * 数据库管理工具类
 *
 * @author GaoHuanjie
 */
public class DBlink {
	
	private Logger logger = Logger.getLogger(DBlink.class);
	
	/**
	 * 获取数据库连接
	 *
	 * @author GaoHuanjie
	 */
	private Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");//加载驱动
			String userName = PropertiesTool.getValue("db.username");
			String password = PropertiesTool.getValue("db.password");
			String url = PropertiesTool.getValue("db.url");
			return DriverManager.getConnection(url, userName, password);//获取连接
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 判断SQL语句是否能查出数据
	 *
	 * @author GaoHuanjie
	 */
	public boolean exist(String sql) {
		Connection connection = null;
		Statement statement =null;
		ResultSet resultSet=null;
		try {
			connection = getConnection();//获取连接
			statement = connection.createStatement();
			resultSet= statement.executeQuery(sql);//执行sql,将查询的数据存到ResultSet类型的变量中
			return resultSet.next();
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}finally {
			close(resultSet,statement,connection);
		}
		return false;
	}
	
	/**
	 * 判断SQL语句是否能查出数据
	 *
	 * @author GaoHuanjie
	 */
	public boolean exist(String sql, Object ...params) {
		Connection connection = null;
		PreparedStatement preparedStatement =null;
		ResultSet resultSet=null;
		try {
			connection = getConnection();//获取连接
			preparedStatement = connection.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				preparedStatement.setObject(i+1, params[i]);
			}
			resultSet= preparedStatement.executeQuery();//执行sql,将查询的数据存到ResultSet类型的变量中
			return resultSet.next();
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}finally {
			close(resultSet,preparedStatement,connection);
		}
		return false;
	}
	
	/**
	 * 查询数据
	 *
	 * @author GaoHuanjie
	 */
	public void select(String sql,IRowMapper rowMapper) {//接口无法创建对象,所以rowMapper参数一定指向IRowMapper接口实现类对象
		Connection connection = null;
		Statement statement =null;
		ResultSet resultSet=null;
		try {
			connection = getConnection();//获取连接
			statement = connection.createStatement();
			resultSet= statement.executeQuery(sql);//执行sql,将查询的数据存到ResultSet类型的变量中
			rowMapper.rowMapper(resultSet);//因为rowMapper参数指向IRowMapper接口实现类对象,所以此处将调用接口实现类中所实现的rowMapper方法  多态
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}finally {//释放资源
			close(resultSet,statement,connection);
		}
	}
	
	/**
	 * 查询数据
	 *
	 * @author GaoHuanjie
	 */
	public void select(String sql,IRowMapper rowMapper,Object ...params) {
		Connection connection = null;
		PreparedStatement preparedStatement =null;
		ResultSet resultSet=null;
		try {
			connection = getConnection();//获取连接
			preparedStatement= connection.prepareStatement(sql);//含有?号占位符的sql
			for (int i = 0; i < params.length; i++) {
				preparedStatement.setObject(i+1, params[i]);//为?号赋值
			}
			resultSet= preparedStatement.executeQuery();//执行sql
			rowMapper.rowMapper(resultSet);//因为rowMapper参数指向IRowMapper接口实现类对象,所以此处将调用接口实现类中所实现的rowMapper方法  多态
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}finally {//释放资源
			close(resultSet,preparedStatement,connection);
		}
	}

	/**
	 * 修改(insert、update和delete)数据
	 *
	 * @author GaoHuanjie
	 */
	public boolean update(String sql) {
		Connection connection = null;
		Statement statement = null;
		try {
			connection = getConnection();//获取数据库连接对象,一个对象表示一次数据库连接
			statement = connection.createStatement();//获取Statement对象
			int result = statement.executeUpdate(sql);//执行sql语句,返回受影响的行数,仅限于数据insert、update和delete
			return result>0;//处理结果
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}finally {//即便有异常也会执行代码
			close(statement,connection);
		}
		return false;
	}
	
	/**
	 * 修改(insert、update和delete)数据
	 *
	 * @author GaoHuanjie
	 */
	public boolean update(String sql,Object ...params) {
		Connection connection= null;
		PreparedStatement preparedStatement= null;
		try {
			connection= getConnection();
			preparedStatement= connection.prepareStatement(sql);//含有?号占位符的sql
			for (int i = 0; i < params.length; i++) {
				preparedStatement.setObject(i+1, params[i]);//为?号赋值
			}
			return preparedStatement.executeUpdate()>0;
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}finally {
			close(preparedStatement,connection);
		}
		return false;
	}
	
	/**
	 * 释放资源
	 *
	 * @author GaoHuanjie
	 */
	private void close(Statement statement,Connection connection) {
		try {
			if(statement!=null) {//有可能由于异常导致statement没有赋值,比如url出错
				statement.close();
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(), e);
		}
		try {
			if(connection!=null) {
				connection.close();
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(), e);
		}
	}
	
	/**
	 * 释放资源
	 *
	 * @author GaoHuanjie
	 */
	private void close(ResultSet resultSet,Statement statement,Connection connection) {//重载
		try {
			if(resultSet!=null) {
				resultSet.close();
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(), e);
		}
		close(statement,connection);
	}
}

IRowMapper(接口)

package com.jd.Tool.db;

import java.sql.ResultSet;

public interface IRowMapper {

	void rowMapper(ResultSet rs);
}

MD5Tool(加密—src根目录)

package com.jd.Tool;

import java.math.BigInteger;
import java.security.MessageDigest;

public class MD5Tool {
	
	public static String encrypt(String password) {
		byte[] bytes = null;
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(password.getBytes());//加密
			bytes = messageDigest.digest();//获得加密结果
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String result = new BigInteger(1, bytes).toString(16);// 将加密后的数据转换为16进制数字
		// 生成数字未满32位,则前面补0
		for (int i = 0; i < 32 - result.length(); i++) {
			result = "0" + result;
		}
		return result;
	}
}

PropertiesTool(src根目录)

package com.jd.Tool;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesTool {
	
	private static Properties properties = new Properties();
	
	//此静态代码块,用于将db.properties中的变量转移到一个固定方法中
	static {
		InputStream inputStream = Properties.class.getClassLoader().getResourceAsStream("db.properties");//将db.properties变为java中inputStream对象
		try {
			properties.load(inputStream);//将inputStream放到load方法中
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/*public static void main(String[] args) {
		 String userName = properties.getProperty("db.username");
	}*/
	
	public static String getValue(String key) {//key为db.properties中所有变量
		return properties.getProperty(key);
	}

}

三、Main包

package com.jd.Main;

import java.util.Scanner;
import java.util.UUID;

import com.jd.Tool.MD5Tool;
import com.jd.Tool.db.DBlink;

/*
 * 
 */
public class Main {

	public static void main(String[] args) {
		System.out.println("*********************************");
		System.out.println("*\t\t\t\t*");
		System.out.println("*\t欢迎使用注册登录系统\t*");
		System.out.println("*\t\t\t\t*");
		System.out.println("*********************************");
		while (true) {
			menu();
		}
	}

	static void menu() {
		System.out.println("1、注册");//用户名 密码 确认密码
		System.out.println("2、登录");//用户名和密码
		System.out.println("3、退出");//System.exit(0);
		System.out.println("请输入操作,以Enter键结束:");
		Scanner scanner = new Scanner(System.in);
		int option  = scanner.nextInt();
		switch (option) {
			case 1:{
				System.out.println("请输入用户名");
				String userName=scanner.next();
				System.out.println("请输入密码");
				String password=scanner.next();
				System.out.println("请确认密码");
				String rePassword=scanner.next();
				String sql = "select id from user_infor where user_name=?";
				if(new DBlink().exist(sql,userName)) {
					System.out.println("用户名被占用,操作终止!");
					return;
				}
				if(!password.equals(rePassword)) {
					System.out.println("密码与确认密码不一致,操作终止!");
					return;
				}
				String id = UUID.randomUUID().toString();//产生一个全球唯一随机数
				password = MD5Tool.encrypt(rePassword);//加密——可用百度md5解密
				sql="insert into user_infor (id,user_name,password) value ('"+id+"',?,?)";
				if(new DBlink().update(sql,userName,password)) {
					System.out.println("注册成功!");
					return;
				}
				System.out.println("注册失败!");
				break;
			}
			case 2:{
				System.out.println("请输入用户名");
				String userName=scanner.next();
				System.out.println("请输入密码");
				String password=scanner.next();
				String sql = "select id from user_infor where user_name=? and password=?";
				if(new DBlink().exist(sql,userName,password)) {
					System.out.println("登录成功!");
					return;
				}
				System.out.println("用户名或密码错误,登录失败!");
				break;
			}
			case 3:{
				System.out.println("已退出系统!");
				System.exit(0);
				break;
			}
			
			default:
				System.out.println("I'm Sorry,there is not the "+option+" option,please try again.");
		}
	}
}

 

你可能感兴趣的:(实现用户注册和登录系统)