纯Java 写一个信息管理系统

前言

我们日常开发中都是都是使用各种框架集成进行web开发,当然纯java也能实现一个系统

今天我们就实现一个 在cmd 命令上实现的

开发技术

  • Java SE
  • Mysql
  • JDBC

开发工具

eclipse

Eclipse 是一个开放源代码的、基于Java的可扩展开发平台。就其本身而言,它只是一个框架和一组服务,用于通过插件组件构建开发环境。幸运的是,Eclipse 附带了一个标准的插件集,包括Java开发工具(Java Development Kit,JDK)。

当然作者平时都是使用Idea进行开发,因为idea对于开发者来说是真的想

如果你也需要一个 Jetbrain  IDE 全家桶,place 看下面文章:

推荐文章

IDEA工具JetBrains产品全版本激活教程
前言 IDEA 全称 IntelliJ IDEA,是java编程语言开发的集成环境。IntelliJ在业界被公认为最好的java开发工具,尤其在智能代码助手、代码自动提示、重构、JavaEE……

代码实现

封装jdbc工具类

db.properties

Driver = com.mysql.jdbc.Driver
URL = jdbc:mysql://127.0.0.1:3306/test
USERNAME = 数据库用户名
PASSWORD = 数据库密码

BaseDao

package app.jdbc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.PropertyResourceBundle;

public class BaseDao {
	private static String Driver;// 驱动
	private static String URL;// 地址ַ
	private static String USERNAME;// 数据库用户名
	private static String PASSWORD;// 数据库密码
	private static PropertyResourceBundle  resourceBundle;

	public static void init() {
		try {
			resourceBundle = new PropertyResourceBundle(
					BaseDao.class.getResourceAsStream("db.properties"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// properties.list(System.out);
		BaseDao.Driver = resourceBundle.getString("Driver");
		BaseDao.URL = resourceBundle.getString("URL");
		BaseDao.USERNAME = resourceBundle.getString("USERNAME");
		BaseDao.PASSWORD = resourceBundle.getString("PASSWORD");
	}

	// 打开链接
	public static Connection getcon() {
		BaseDao.init();
		Connection con = null;
		try {
			Class.forName(Driver);// 加载驱动
			con = DriverManager.getConnection(URL, USERNAME, PASSWORD);// 打开链接
			System.out.println("数据库连接中。。。");
			if (con != null) {
				System.out.println("连接成功!\n");
			} else {
				System.out.println("连接失败!");
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return con;
	}

	// 执行增加删除修改
	public static int excute(String sql, Object... obj) {
		// TODO Auto-generated method stub
		int num = -1;
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet r = null;
		try {
			con = getcon();
			ps = con.prepareStatement(sql);
			if (obj != null) {
				for (int i = 0; i < obj.length; i++) {
					ps.setObject(i + 1, obj[i]);
				}
			}
			num = ps.executeUpdate();
			System.out.println(sql);
			System.out.println("(" + num + "(rows) affected" + ")");
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeAll(con, ps, r);
		}
		return num;
	}

	// 释放资源
	public static void closeAll(Connection con, PreparedStatement ps,
			ResultSet r) {
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (r != null) {
			try {
				r.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

dao层

package app.dao;

import java.util.List;

import app.bean.User;

public interface UserDao {
	//条件查询用户
	public User queryByNameOrPass(User user);
	//注册
	public int register(User user);
	//修改
	public int update(User user);
	//删除
	public int delete(Integer id);
	//判断注册是否重复
	public int queryCountbyUserName(String username);
	//条件查询所有
	public List<User> queryAllByExample(User user);
	
}
package app.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import app.jdbc.BaseDao;
import app.bean.User;
import app.dao.UserDao;

public class UserDaoImpl implements UserDao {

	@Override
	public User queryByNameOrPass(User user) {
		// TODO Auto-generated method stub
		Connection con =null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		User newUser = new User();
		String sql = "select * from user ";
		System.out.println("\n"+user+"\n");
		if (user.getId() != null) {
			 if (user.getUsername() == null && user.getPassword() != null) {
				sql += "where id='" + user.getId()+"' and password='"+user.getPassword() + "'";
			}else if (user.getUsername() != null && user.getPassword() == null) {
				sql += "where id='" + user.getId()+ "' and username='" + user.getUsername() + "'";
			}else {
				sql += "where id='" + user.getId()+ "'";
			}
		}else {
			if (user.getUsername()!= null && user.getPassword() != null) {
				sql += "where username='" + user.getUsername() + "' and password='" + user.getPassword() + "'";
			}
			if (user.getUsername()!= null && user.getPassword() == null) {
				sql += "where username='" + user.getUsername() + "'";
			}else if (user.getUsername()== null && user.getPassword() != null){
				sql += "where password='" + user.getPassword() + "'";
			}
		}
		try {
			con =BaseDao.getcon();
			ps =con.prepareStatement(sql);
			rs=ps.executeQuery();
			System.out.println(sql);
			while(rs.next()){
				newUser.setId(rs.getInt("id"));
				newUser.setUsername(rs.getString("username"));
				newUser.setPassword(rs.getString("password"));
				newUser.setRole(rs.getString("role"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			BaseDao.closeAll(con, ps, rs);
		}
		if (newUser.getId() == null){
			return null;
		}
		return newUser;
	}
	
	@Override
	public int queryCountbyUserName(String username) {
		// TODO Auto-generated method stub
		Connection con =null;
		PreparedStatement ps=null;
		ResultSet r=null;
		int num=0;
		try {
			con =BaseDao.getcon();
			String sql = "select count(*) as count from user where username='"+username+"'";
			ps =con.prepareStatement(sql);
			r=ps.executeQuery();
			while(r.next()){
				num=r.getInt("count");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			BaseDao.closeAll(con, ps, r);
		}
		return num;
	}
	@Override
	public int register(User user) {
		// TODO Auto-generated method stub
		System.out.println(user.getUsername());
		String sql = "insert into user (username,password)values(?,?)";
		Object[] obj = {user.getUsername(),user.getPassword()};
		int num =BaseDao.excute(sql, obj);
		return num;
	}

	@Override
	public int update(User user) {
		// TODO Auto-generated method stub
		int num = 0;
		String sql = "update user set";
		if (user.getUsername()!= null && user.getPassword() != null && user.getRole() != null) {
			sql += " username = ?, password = ?, role = ? where id =?";
			Object[] obj = {user.getUsername(),user.getPassword(),user.getRole(),user.getId()};
			num =BaseDao.excute(sql, obj);
		}else if (user.getUsername()!= null && user.getPassword() == null && user.getRole() == null) {
			sql += " username = ?  where id =?";
			Object[] obj = {user.getUsername(),user.getId()};
			num =BaseDao.excute(sql, obj);
		}else if (user.getUsername()== null && user.getPassword() != null && user.getRole() == null) {
			sql += " password = ? where id = ?";
			Object[] obj = {user.getPassword(),user.getId()};
			num =BaseDao.excute(sql, obj);
		}else if (user.getUsername() == null && user.getPassword() == null && user.getRole() != null) {
			sql += " role = ? where id = ?";
			Object[] obj = {user.getRole(),user.getId()};
			num =BaseDao.excute(sql, obj);
		}else if (user.getUsername()!= null && user.getPassword() != null && user.getRole() == null) {
			sql += " username = ?,password = ?  where id =?";
			Object[] obj = {user.getUsername(),user.getPassword(),user.getId()};
			num =BaseDao.excute(sql, obj);
		}else if (user.getUsername()!= null && user.getPassword() == null && user.getRole() != null) {
			sql += " username = ?,role = ? where id =?";
			Object[] obj = {user.getUsername(),user.getRole(),user.getId()};
			num =BaseDao.excute(sql, obj);
		}else if (user.getUsername() == null && user.getPassword() != null && user.getRole() != null) {
			sql += " password = ?,role = ? where id =?";
			Object[] obj = {user.getUsername(),user.getPassword(),user.getRole(),user.getId()};
			num =BaseDao.excute(sql, obj);
		}
		return num;
	}

	@Override
	public int delete(Integer id) {
		// TODO Auto-generated method stub
		String sql = "delete from user where id = ?";
		Object[] obj = {id};
		int num =BaseDao.excute(sql, obj);
		return num;
	}

	@Override
	public List<User> queryAllByExample(User user) {
		// TODO Auto-generated method stub
		List<User> users = new ArrayList<User>();
		Connection con =null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		String sql = "select * from user ";; 
		System.out.println(user);
		if (user != null) {
			if (user.getId() != null) {
				 if (user.getUsername() == null && user.getPassword() != null) {
					sql += "where id='" + user.getId()+"' and password='"+user.getPassword() + "'";
				}else if (user.getUsername() != null && user.getPassword() == null) {
					sql += "where id='" + user.getId()+ "' and username='" + user.getUsername() + "'";
				}else {
					sql += "where id='" + user.getId()+ "'";
				}
			}else {
				if (user.getUsername()!= null && user.getPassword() != null) {
					sql += "where username='" + user.getUsername() + "' and password='" + user.getPassword() + "'";
				}
				if (user.getUsername()!= null && user.getPassword() == null) {
					sql += "where username='" + user.getUsername() + "'";
				}else if (user.getUsername()== null && user.getPassword() != null){
					sql += "where password='" + user.getPassword() + "'";
				}
			}
		}
		
		System.out.println(sql);
		try {
			con =BaseDao.getcon();
			ps =con.prepareStatement(sql);
			rs=ps.executeQuery();
			System.out.println(sql);
			while(rs.next()){
				User newUser = new User();
				newUser.setId(rs.getInt("id"));
				newUser.setUsername(rs.getString("username"));
				newUser.setPassword(rs.getString("password"));
				newUser.setRole(rs.getString("role"));
				users.add(newUser);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			BaseDao.closeAll(con, ps, rs);
		}
		return users;
	}

}

service层

package app.service;

import java.util.List;

import app.bean.User;

public interface UserService {
	public User login(User user);
	public boolean register(User user);
	public boolean update(User user);
	public boolean delete(Integer id);
	public User queryByNameOrPass(User user);
	//多条件查询所有
	public List<User> queryAllByExample(User user);	
}
package app.service.impl;

import java.util.List;

import app.bean.User;
import app.dao.UserDao;
import app.dao.impl.UserDaoImpl;
import app.service.UserService;

public class UserServiceImpl implements UserService{
	UserDao userDao = new UserDaoImpl();

	@Override
	public User login(User user) {
		// TODO Auto-generated method stub
		User newUser=userDao.queryByNameOrPass(user);
		if (newUser != null) {
			return newUser;
		} else {
			return null;
		}
	}

	@Override
	public boolean register(User user) {
		// TODO Auto-generated method stub
		int num = userDao.queryCountbyUserName(user.getUsername());
		int i = 0;
		if (num == 0) {
			i = userDao.register(user);	
		}
		if (i == 1) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean update(User user) {
		// TODO Auto-generated method stub
		return userDao.update(user)== 1?true:false;
	}

	@Override
	public boolean delete(Integer id) {
		// TODO Auto-generated method stub
		return userDao.delete(id)== 1?true:false;
	}

	@Override
	public List<User> queryAllByExample(User user) {
		// TODO Auto-generated method stub
		return userDao.queryAllByExample(user);
	}

	@Override
	public User queryByNameOrPass(User user) {
		// TODO Auto-generated method stub
		return userDao.queryByNameOrPass(user);
	}
}

main App主类

package app;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Scanner;

import app.bean.User;
import app.service.UserService;
import app.service.impl.UserServiceImpl;



public class App {
	//存储在线用户
	private static Map<Integer,User> onlineMap = new HashMap<Integer,User>();
	// 键盘输入
	private static Scanner sc = new Scanner(System.in);
	private static int num = 0;
	// 用户业务层
	private static UserService userService =new UserServiceImpl();
	// 当前登录用户
	private static User currentUser = new User();
	// 操作用户
	private static User user = new User();
	/**
	 * 集合的遍历案例 与  数据库测试案例
	 * **/
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("-------------------信息修改系统登录-------------------\n");
		if (currentUser.getId() == null) {
			login:
			while(true){
				System.out.println("\t\t\t1,注册");
				System.out.println("\t\t\t2,登录");
				System.out.println("\t\t\t0,结束");
				System.out.print("请选择:");
				int num =sc.nextInt();
				System.out.println("");
				//注册
				if(num ==1){
					System.out.println("请输入用户名");
					user.setUsername(sc.next());
					System.out.println("请输入密码");
					user.setPassword(sc.next());
					boolean res = userService.register(user);
					if (res) {
						System.out.println("注册成功!");
						user = new User();
					} else {
						System.err.println("注册失败");
					}
				}
				//登录
				if(num == 2){
					System.out.println("请输入用户名");
					user.setUsername(sc.next());
					System.out.println("请输入密码");
					user.setPassword(sc.next());
					currentUser =userService.login(user);
					if(currentUser == null){
						System.out.println("用户名不存在或密码错误");
					}else{
						System.out.println("登录成功");
						user = new User();
						onlineMap.put(currentUser.getId(), currentUser);
						menu();
					}
				}
				//退出系统
				if(num == 0){
					System.out.println("程序结束!");
					onlineMap.remove(user.getId());
					break login;
				}
			}
		}
	}
	public static void menu() {
		index:
		while(true){
			System.out.println("-------------------欢迎来到信息修改系统-------------------\n");
			System.out.println("\t\t\t1,个人信息");
			System.out.println("\t\t\t2,修改密码");
			System.out.println("\t\t\t3,在线用户");
			if ("ROLE_ADMIN".equals(currentUser.getRole())) {
				System.out.println("\t\t\t4,增加用户");
				System.out.println("\t\t\t5,删除用户");
				System.out.println("\t\t\t6,修改用户");
				System.out.println("\t\t\t7,查询用户");
				System.out.println("\t\t\t8,查询所有用户");
			}
			System.out.println("\t\t\t0,退出登录");
			System.out.print("请选择:");
			num =sc.nextInt();
			System.out.println("");
			user = new User();
			//鉴权
			if (num == 4 || num == 5 || num == 6 || num == 7 || num == 8) {
				if ( !"ROLE_ADMIN".equals(currentUser.getRole())) {
					System.out.println("抱歉你没有权限");
					continue;
				}
			}
			//个人信息
			if(num == 1){
				System.out.println("----------------------个人用户信息:----------------------");
				System.out.println("用户ID:"+currentUser.getId()+"\n用户名:"+currentUser.getUsername()+"\n密码:"+currentUser.getPassword()+"\n角色:"+("ROLE_ADMIN".equals(currentUser.getRole())?"超级管理员":"普通用户"));
			}
			//修改密码
			if(num == 2){
				user.setId(currentUser.getId());
				System.out.println("请输入旧密码");
				String old = sc.next();
				user.setPassword(old);
				User isExited = userService.queryByNameOrPass(user);
				if(isExited != null) {
					System.out.println("请输入新密码");
					user.setPassword(sc.next());
				}else {
					System.out.println("密码验证错误");
					continue;
				}
				System.out.println("\n是否修改?(Y/N)");
				if ("y".equals(sc.next())) {
					boolean res = userService.update(user);
					if (res) {
						System.out.println("密码修改成功!!!");
						user = new User();
					} else {
						System.err.println("密码修改失败");
					}
				}else {
					System.out.println("\n已取消");
					continue;
				}
			}
			//在线用户
			if(num == 3){
				System.out.println("在线用户:");
				onlineMap.forEach((k,v) -> {
					User us = v;
					System.out.println(us.getId()+"\t"+us.getUsername()+"\t"+us.getPassword()+"\t"+("ROLE_ADMIN".equals(us.getRole())?"超级管理员":"普通用户"));
				});
			}
			//增加用户
			if(num == 4){
				System.out.println("请输入用户名");
				user.setUsername(sc.next());
				System.out.println("请输入密码");
				user.setPassword(sc.next());
				System.out.println("请选择角色:0:管理员/1:普通用户");
				int num = sc.nextInt();
				user.setRole(num == 0 ? "ROLE_ADMIN" : "ROLE_USER");
				System.out.println("\n是否添加?(Y/N)");
				if ("y".equals(sc.next())) {
					boolean res = userService.register(user);
					if (res) {
						System.out.println("增加成功!");
						user = new User();
					} else {
						System.err.println("增加失败");
					}
				}else {
					System.out.println("\n已取消");
					continue;
				}
			}
			//删除用户
			if(num == 5){
				System.out.println("请输入要删除信息的id");
				user.setId(sc.nextInt());
				System.out.println("\n是否删除?(Y/N)");
				if ("y".equals(sc.next())) {
					boolean res = userService.delete(user.getId());
					if (res) {
						System.out.println("删除成功!");
						user = new User();
					} else {
						System.err.println("删除失败");
					}
				}else {
					System.out.println("\n已取消");
					continue;
				}
				
			}
			//修改用户
			if(num == 6){
				System.out.println("请输入要修改信息的id");
				user.setId(sc.nextInt());
				user = userService.queryByNameOrPass(user); 
				System.out.println("您需要修改的信息如下:");
				System.out.println("用户ID:"+user.getId()+"\n用户名:"+user.getUsername()+"\n密码:"+user.getPassword()+"\n角色:"+("ROLE_ADMIN".equals(user.getRole())?"超级管理员":"普通用户"));
				System.out.println("\n是否修改?(Y/N)");
				if ("y".equals(sc.next())) {
					System.out.println("请输入修改的用户名");
					user.setUsername(sc.next());
					System.out.println("请输入修改的密码");
					user.setPassword(sc.next());
					System.out.println("请选择角色:0:管理员/1:普通用户");	
					int num = sc.nextInt();
					user.setRole(num == 0 ? "ROLE_ADMIN" : "ROLE_USER");
				}else {
					System.out.println("\n已取消");
					continue;
				}
				System.out.println("\n是否添加?(Y/N)");
				if ("y".equals(sc.next())) {
					boolean res = userService.delete(user.getId());
					if (res) {
						System.out.println("修改成功!");
						user = new User();
					} else {
						System.err.println("删除失败");
					}
				}else {
					System.out.println("\n已取消");
					continue;
				}
			}
			//条件查询用户
			if(num == 7){
				System.out.println("请选择查询:(0:单条件查询/1:多条件查询)");
				int num = sc.nextInt();
				if (num == 0) {
					System.out.println("单条件查询条件:(0:id/1:用户名/2:密码/3:角色)");
					int a = sc.nextInt();
					if (a == 0) {
						System.out.println("请输入要查询的id");
						user.setId(sc.nextInt());
					}
					if (a == 1) {
						System.out.println("请输入要查询的用户名");
						user.setUsername(sc.next());
					}
					if (a == 2) {
						System.out.println("请输入要查询的密码");
						user.setPassword(sc.next());
					}
					if (a == 3) {
						System.out.println("请输入要查询的角色(0/1)");
						int b = sc.nextInt();
						user.setRole(num == 0 ? "ROLE_ADMIN" : "ROLE_USER");
					}
				}else {
					System.out.println("多条件查询条件:(0:(id+用户名)/1:(id+密码)/2:(id+角色)/3:(用户名+密码)/4:(用户名+角色)/5:(密码+角色)/6:全条件)");
					int c = sc.nextInt();
					if (c == 0) {
						System.out.println("请输入要查询的id");
						user.setId(sc.nextInt());
						System.out.println("请输入要查询的用户名");
						user.setUsername(sc.next());
					}
					if (c == 1) {
						System.out.println("请输入要查询的id");
						user.setId(sc.nextInt());
						System.out.println("请输入要查询的密码");
						user.setPassword(sc.next());
					}
					if (c == 2) {
						System.out.println("请输入要查询的id");
						user.setId(sc.nextInt());
						System.out.println("请输入要查询的角色(0/1)");
						int b = sc.nextInt();
						user.setRole(num == 0 ? "ROLE_ADMIN" : "ROLE_USER");
					}
					if (c == 3) {
						System.out.println("请输入要查询的用户名");
						user.setUsername(sc.next());
						System.out.println("请输入要查询的密码");
						user.setPassword(sc.next());
					}
					if (c == 4) {
						System.out.println("请输入要查询的用户名");
						user.setUsername(sc.next());
						System.out.println("请输入要查询的角色(0/1)");
						int b = sc.nextInt();
						user.setRole(num == 0 ? "ROLE_ADMIN" : "ROLE_USER");
					}
					if (c == 5) {
						System.out.println("请输入要查询的密码");
						user.setPassword(sc.next());
						System.out.println("请输入要查询的角色(0/1)");
						int b = sc.nextInt();
						user.setRole(num == 0 ? "ROLE_ADMIN" : "ROLE_USER");
					}
					
					if (c == 6) {
						System.out.println("请输入要查询的id");
						user.setId(sc.nextInt());
						System.out.println("请输入要查询的用户名");
						user.setUsername(sc.next());
						System.out.println("请输入要查询的密码");
						user.setPassword(sc.next());
						System.out.println("请输入要查询的角色(0/1)");
						int b = sc.nextInt();
						user.setRole(num == 0 ? "ROLE_ADMIN" : "ROLE_USER");
					}
				}	
				List<User> res = userService.queryAllByExample(user);
				if (res.size() != 0) {
					res.forEach(Item -> {
						System.out.println(Item.getId()+"\t"+Item.getUsername()+"\t"+Item.getPassword()+"\t"+("ROLE_ADMIN".equals(Item.getRole())?"超级管理员":"普通用户"));
					});
				}else {
					System.out.println("\n暂无数据8");
					continue;
				}
				
			}
			//查询数据库所有信息
			if(num == 8){
				List<User> list=userService.queryAllByExample(null);
				System.out.println("\n----------------------用户信息:----------------------\n\n\n");
				System.out.println("用户\t\t用户名\t\t密码\t\t角色\n");
				for (User us : list) {
					System.out.println(us.getId()+"\t\t"+us.getUsername()+"\t\t"+us.getPassword()+"\t\t"+("ROLE_ADMIN".equals(us.getRole())?"超级管理员":"普通用户")+"\n");
				}
			}
			//退出登录
			if(num == 0){
				System.out.println("您已成功退出系统!");
				onlineMap.remove(currentUser.getId());
				break index;
			}
			System.out.println("\n是否继续?(Y/N)");
			if ("y".equals(sc.next())) {
				continue;
			}else {
				System.out.println("您已成功退出系统!");
				break index;
			}
		}
	}
}

效果图

阅读剩余
THE END