注册登录系统(含MD5加密,注册、登录、推出、注销账号)

3 篇文章 0 订阅
3 篇文章 0 订阅

不废话,直接干

用户管理系统—登录(Login)篇(含MD5加密)

要引用的jar包有mysql-connector-java-5.1.44-bin.jar和log4j-1.2.15.jar(都可以在网上找到)

一、项目截图:
在这里插入图片描述

Main类

package com.jd.test;

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\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("4、注销账号");//用户名 密码
		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();
				if(!password.equals(rePassword)){
					System.out.println("两次密码不一致,操作终止!");
					return;
				}
				/**
				 * 查询用户名是否已存在 
				 */
				String sql = "select id from user_info where user_name = ?";
				if(new DBLink().exist(sql, userName)) {
					System.out.println("用户名已存在,操作终止!");
					return;
				}
				String id = UUID.randomUUID().toString();
				
				/**
				 * 加密密码 
				 */
				password = MD5Tool.encrypt(password);
				sql = "insert into user_info (id,user_name,password) values ('"+id+"',?,?)";
				if(new DBLink().update(sql, userName,password)) {
					System.out.println("注册成功!");
					return;
				}
				System.out.println("注册失败!");
				break;
			}
			case 2:{
				System.out.println("登录");
				System.out.println("请输入用户名:");
				String userName = scanner.next();
				System.out.println("请输入密码:");
				String password = scanner.next();
				/**
				 * 再次加密,此时与原来加密的密码一样,可以登录 
				 */
				password = MD5Tool.encrypt(password);
				String sql = "select id from user_info 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);
			}
			case 4:{
				System.out.println("请输入要注销的用户名:");
				String userName = scanner.next();
				System.out.println("请输入要注销账号的密码:");
				String password = scanner.next();
				password = MD5Tool.encrypt(password);
				/**
				 * 删除(注销)账号 
				 */
				String sql = "delete from user_info where user_name = ? and password = ?";
				if(new DBLink().update(sql, userName,password)) {
					System.out.println("注销账号成功");
					return;
				}
				System.out.println("用户名或密码错误,注销失败!");
				break;
			}
			default:
				System.out.println("I'm Sorry,there is not the "+option+" option,please try again.");
		}
	}
}

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 ZhaoZhengyi
 */

public class DBLink {
	
	private Logger logger = Logger.getLogger(DBLink.class);
	
	/**
	 * 获取数据库连接
	 *
	 * @author ZhaoZhengyi
	 */
	public  Connection getConnection() {
		try {
			String driver = PropertiesTool.getValue("db.driver");
			String   url    = PropertiesTool.getValue("db.url");
			String userName = PropertiesTool.getValue("db.userName");
			String password = PropertiesTool.getValue("db.password");
			Class.forName(driver);
			return DriverManager.getConnection(url, userName, password);
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 该方法用于判断某个用户是否存在,若存在返回该用户数据,否则返回false
	 * @param sql 是指要执行的SQL语句
	 * @return
	 */
	/*public boolean exist(String sql) {
		//初始化变量为null
		Connection connection = null;
		Statement statement = null;
		ResultSet resultset = null;
		try {
			connection = getConnection();
			statement = connection.createStatement();//创建SQL语句对象		
			resultset = statement.executeQuery(sql);//executeQuery用于查询用户的数据,并将其存入ResultSet类型的resultset变量中去
		
			return resultset.next();//若有则返回该用户数据
					
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		} finally {//即便有异常也会执行代码
			close(resultset,statement,connection);//释放资源
		}
		return false;
	}*/
	
	/**
	 * 判断某条数据是否存在
	 *
	 * @author ZhaoZhengyi
	 */
	public boolean exist(String sql,Object ...params) {
		//初始化变量为null
		Connection connection = null;
		PreparedStatement prepareStatement = null;
		ResultSet resultset = null;
		try {
			connection = getConnection();
			prepareStatement = connection.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				prepareStatement.setObject(i+1, params[i]);
			}
			resultset = prepareStatement.executeQuery();//executeQuery用于查询用户的数据,并将其存入ResultSet类型的resultset变量中去
		
			return resultset.next();//若有则返回该用户数据
					
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		} finally {//即便有异常也会执行代码
			close(resultset,prepareStatement,connection);//释放资源
		}
		return false;//若没有则返回false
	}
	
	/**
	 * 该方法用于insert(添加)、delete(删除)、update(修改)用户信息
	 * 至于选哪一个来操作用户信息因sql语句而定
	 * @param sql 是指要操作的SQL语句
	 * @return 若成功则返回影响的行数,否则返回false
	 */
	public boolean update(String sql) {
		Connection connection = null;
		Statement statement = null;
		try {
			connection = getConnection();
			statement = connection.createStatement();//创建SQL语句对象		
			int affect = statement.executeUpdate(sql);//执行sql语句,返回影响的行数,仅限于insert delete update
			/*statement.close();
		      connection.close();*///如果上面代码出现异常,则该行代码及其下面代码无法执行,所以资源无法释放;比如sql语句语法错误,则statement和connection无法释放
			return affect>0;
			
	   /*
		* 这里我想说明一下,由于finally的特殊性,会先执行完finally里的释放资源,再执行上一语句:返回一个affect值
		* 总之就是在结束方法之前无论如何都要先释放资源才可以
		*/
			
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		} finally {//即便有异常也会执行代码
			close(statement,connection);//释放资源
		}
		return false;
	}
	
	/**
	 * 用于添加、删除、修改用户信息
	 *
	 * @author ZhaoZhengyi
	 */
	public boolean update(String sql, Object ...params) {
		Connection connection = null;
		PreparedStatement  prepareStatement = null;
		try {
			connection = getConnection();
			prepareStatement = connection.prepareStatement(sql);//含有?的sql语句 赋值给prepareStatement
			for(int i = 0; i < params.length; i++) {
				prepareStatement.setObject(i+1, params[i]);//用参数替换掉?
			}
		
			int affect = prepareStatement.executeUpdate();//执行sql语句,并返回影响的行数
			return affect>0;
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		} finally {
			close(prepareStatement,connection);
		}
		return false;
	}
	
	
	
	/**
	 * 该方法用于查询用户信息
	 * @param sql 要执行的SQL语句
	 * @param rowMapper 接口是无法创建对象的,所以参数rowMapper一定指向接口(IRowMapper)实现类对象
	 */
	/*public void select(String sql,IRowMapper rowMapper) {
		Connection connection = null;
		Statement statement = null;
		ResultSet resultset = null;
		try {
			connection = getConnection();
			statement = connection.createStatement();//创建SQL语句对象
			resultset = statement.executeQuery();//执行SQL语句,此时用户数据都在resultset里面
			rowMapper.rowMapper(resultset);//因为rowMapper参数指向IRowMapper接口实现类对象,所以此处将调用接口实现类中所实现的rowMapper方法  多态
			
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		} finally {
			close(resultset,statement,connection);//释放资源
		}
		
	}*/
	
	/**
	 * 查询用户数据
	 *
	 * @author ZhaoZhengyi
	 */
	public void select(String sql,IRowMapper rowMapper,Object ...params) {
		Connection connection = null;
		PreparedStatement prepareStatement = null;
		ResultSet resultset = null;
		try {
			connection = getConnection();
			prepareStatement = connection.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				prepareStatement.setObject(i+1, params[i]);
			}
			resultset = prepareStatement.executeQuery();//执行SQL语句,此时用户数据都在resultset里面
			rowMapper.rowMapper(resultset);//因为rowMapper参数指向IRowMapper接口实现类对象,所以此处将调用接口实现类中所实现的rowMapper方法  多态
			
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		} finally {
			close(resultset,prepareStatement,connection);//释放资源
		}
		
	}

	/**
	 * 释放资源
	 *
	 * @author ZhaoZhengyi
	 */
	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 ZhaoZhengyi
	 */
	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;

@FunctionalInterface
public interface IRowMapper {

	/**
	 * 定义一个抽象方法(参数类型为ResultSet)
	 *
	 * @author ZhaoZhengyi
	 */
	void rowMapper (ResultSet rs);
}

PrppertiesTool类

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文件和properties
	 * 
	 * 静态代码块先于main方法先执行
	 */
	static {
		InputStream inputStream = PropertiesTool.class.getClassLoader().getResourceAsStream("db.properties");//将db.properties变为javaIO流对传入到inputStream中
		//此时db.properties文件中的数据就保存到了inputStream中
		try {
			properties.load(inputStream);//将inputStream中的key和value放到load方法中进行解析再存到properties中
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
  
	/**
	 * 我们创建一个getVaule方法来便于调用文件(此时也就是properties)中的数据
	 */
	public static String getValue(String key) {
		return properties.getProperty(key);//返回properties中的key值
	  
	}
  
	/**
	 * 我们来测试一下:
	 */
	public static void main(String [] ages) {
		String userName = getValue("db.userName");
		String password = getValue("db.password");
		String url = getValue("db.url");
		String driver = getValue("db.driver");
		System.out.println(userName);
		System.out.println(password);
		System.out.println(url);
		System.out.println(driver);
	}
}

MD5Tool类

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;
	}
}

db.properties

db.userName = root
db.password = root
db.url = jdbc:mysql://127.0.0.1:3306/test
db.driver = com.mysql.jdbc.Driver

log4j.properties

# DEBUG\u8BBE\u7F6E\u8F93\u51FA\u65E5\u5FD7\u7EA7\u522B\uFF0C\u7531\u4E8E\u4E3ADEBUG\uFF0C\u6240\u4EE5ERROR\u3001WARN\u548CINFO \u7EA7\u522B\u65E5\u5FD7\u4FE1\u606F\u4E5F\u4F1A\u663E\u793A\u51FA\u6765
log4j.rootLogger=DEBUG,Console,RollingFile

#\u5C06\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u63A7\u5236\u53F0
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern= [%-5p]-[%d{yyyy-MM-dd HH:mm:ss}] -%l -%m%n
#\u5C06\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u64CD\u4F5C\u7CFB\u7EDFD\u76D8\u6839\u76EE\u5F55\u4E0B\u7684log.log\u6587\u4EF6\u4E2D
log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingFile.File=D://log.log
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p %-40.40c %X{traceId}-%m%n

创建的表:

在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不动声色的小蜗牛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值