武汉理工 档案管理系统(java实现)
Administrator.javaimport java.io.IOException;import java.sql.SQLException;import java.util.Enumeration;import java.util.Scanner;public class Administrator extends User {public Administrator...
·
Administrator.java
import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Scanner;
public class Administrator extends User {
public Administrator(String name,String password,String role){
super(name,password,role);
}
public boolean changeUserInfo(String name, String password, String role) throws SQLException{
if (DataProcessing.updateUser(name, password, role)){
setName(name);
setPassword(password);
setRole(role);
System.out.println("修改成功\n");
return true;
}else
return false;
}
public void delUser(String name) throws SQLException{
DataProcessing.deleteUser(name);
System.out.println("删除成功\n");
}
public void addUser(String name,String password,String role) {
DataProcessing.insertUser(name,password,role);
}
public void listUser() {
Enumeration<User> e = null;
try {
e = DataProcessing.getAllUser();
} catch (SQLException e1) {
System.out.println("数据库错误" + e1.getMessage());
}
User user;
while(e.hasMoreElements()) {
user = e.nextElement();
System.out.println("用户名:" + user.getName() + " 密码:" +
user.getPassword() + " 角色:" + user.getRole());
}
}
public void showMenu() {
String tip_administrator = "******欢迎来到系统管理菜单******\n\t" + "1.修改用户\n\t" +
"2.删除用户\n\t" + "3.新增用户\n\t" + "4.列出用户\n\t" + "5.下载文件\n\t" +
"6.文件列表\n\t" + "7.修改(本人)密码\n\t" + "8.退出\n" + "***************************";
String tip_menu = "请选择菜单:";
Scanner in = new Scanner(System.in);
while(true){
System.out.println(tip_administrator);
System.out.println(tip_menu);
int option;
option = in.nextInt();
switch(option) {
case 1:
System.out.println("修改用户");
System.out.println("请输入用户名:");
String name1,password,role;
name1 = in.next();
System.out.println("请输入密码:");
password = in.next();
System.out.println("请输入角色:");
role = in.next();
try {
if(changeUserInfo(name1,password,role))
System.out.println("修改成功!");
else
System.out.println("修改失败!");
} catch (SQLException e) {
System.out.println("数据库错误" + e.getMessage());
}
break;
case 2:
System.out.println("删除用户");
System.out.println("请输入用户名:");
String name2;
name2 = in.next();
try {
delUser(name2);
} catch (SQLException e1) {
System.out.println("数据库错误" + e1.getMessage());
}
break;
case 3:
System.out.println("新增用户");
String name3,password1,role1;
System.out.println("请输入用户名:");
name3 = in.next();
System.out.println("请输入密码:");
password1 = in.next();
System.out.println("请输入角色:");
role1 = in.next();
addUser(name3,password1,role1);
break;
case 4:
System.out.println("列出用户:");
listUser();
break;
case 5:
System.out.println("下载文件");
System.out.println("请输入档案号:");
String filename;
filename = in.next();
try {
downloadFile(filename);
} catch (IOException e) {
System.out.println("文件错误" + e.getMessage());
} catch (SQLException e) {
System.out.println("数据库错误" + e.getMessage());
}
break;
case 6:
try {
showFileList();
} catch (SQLException e) {
System.out.println("数据库错误" + e.getMessage());
}
break;
case 7:
System.out.println("修改(本人)密码");
System.out.println("请输入新口令:");
String password2;
password2 = in.next();
try {
changeSelfInfo(password2);
} catch (SQLException e) {
System.out.println("数据库错误" + e.getMessage());
}
break;
case 8:
exitSystem();
break;
}
}
}
}
Browser.java
import java.io.IOException;
import java.sql.SQLException;
import java.util.Scanner;
public class Browser extends User{
public Browser(String name,String password,String role) {
super(name,password,role);
}
public void showMenu() {
String tip_browser = "******欢迎来到档案浏览菜单******\n\t" + "1.下载文件\n\t" +
"2.文件列表\n\t" + "3.修改密码\n\t" + "4.退出\n" +
"****************************";
String tip_menu = "请选择菜单:";
Scanner in = new Scanner(System.in);
while(true){
System.out.println(tip_browser);
System.out.println(tip_menu);
int option;
option = in.nextInt();
switch(option) {
case 1:
System.out.println("下载文件");
System.out.println("请输入档案号:");
String filename;
filename = in.next();
try {
downloadFile(filename);
} catch (IOException e) {
System.out.println("文件错误" + e.getMessage());
} catch (SQLException e) {
System.out.println("数据库错误" + e.getMessage());
}
break;
case 2:
try {
showFileList();
} catch (SQLException e) {
System.out.println("数据库错误" + e.getMessage());
}
break;
case 3:
System.out.println("修改密码");
System.out.println("请输入新密码:");
String password;
password = in.next();
try {
changeSelfInfo(password);
} catch (SQLException e) {
System.out.println("数据库错误" + e.getMessage()
);
}
break;
case 4:
exitSystem();
break;
}
}
}
}
DataProcessing.java
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import java.sql.*;
public class DataProcessing {
static Connection connection;
static Statement statement;
static ResultSet resultset;
static boolean connectedToDatabase;
static String drivername = "com.mysql.cj.jdbc.Driver";
static String url = "jdbc:mysql://localhost:3306/management";
static String user = "root";
static String password= "xiaoge77";
static {
connectedToDatabase = false;
try {
Class.forName(drivername);
connection = DriverManager.getConnection(url,user,password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connectedToDatabase = true;
System.out.println(connectedToDatabase);
}
public static Doc searchDoc(String ID) {
Timestamp timestamp;
String creator,description,filename;
Doc doc = null;
try {
statement = connection.createStatement();
resultset = statement.executeQuery("select * from doc_info where ID='"+ID+"'");
if(resultset.next()){
creator=resultset.getString("creator");
timestamp=resultset.getTimestamp("timestamp");
description=resultset.getString("description");
filename=resultset.getString("filename");
doc=new Doc(ID,creator,timestamp,description,filename);
return doc;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
synchronized public static Enumeration<Doc> getAllDocs() throws SQLException{
Vector<Doc> vec=new Vector<Doc>();
Doc doc = null;
Timestamp timestamp;
String ID,creator,description,filename;
System.out.println(connectedToDatabase);
if(!connectedToDatabase)
throw new SQLException("Not Connected to Database.");
try {
statement = connection.createStatement();
System.out.println("aaa");
resultset=statement.executeQuery("select * from doc_info");
System.out.println("bbb");
while(resultset.next()){
ID=resultset.getString("ID");
creator=resultset.getString("creator");
timestamp=resultset.getTimestamp("timestamp");
description=resultset.getString("description");
filename=resultset.getString("filename");
doc=new Doc(ID,creator,timestamp,description,filename);
vec.add(doc);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return vec.elements();
}
synchronized public static boolean insertDoc(String ID, String creator, Timestamp timestamp, String description, String filename){
try {
statement = connection.createStatement();
if(statement.executeUpdate("insert into doc_info values('"+ID+"','"+creator+"','"+timestamp+"','"+description+"','"+filename+"')") != 0)
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public static User searchUser(String name){
String password,role;
User user;
try {
statement = connection.createStatement();
resultset=statement.executeQuery("select * from user_info where username='"+name+"'");
if(resultset.next()){
password=resultset.getString("password");
role=resultset.getString("role");
switch(role){
case "administrator":
return user=new Administrator(name,password,role);
case "browser":
return user=new Browser(name,password,role);
case "operator":
return user=new Operator(name,password,role);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static User searchUser(String name, String password){
String role;
User user=null;
try {
statement = connection.createStatement();
resultset=statement.executeQuery("select * from user_info where username='"+name+"' AND"+" password='"+password+"'");
if(resultset.next()){
role=resultset.getString("role");
switch(role){
case "administrator":
return user=new Administrator(name,password,role);
case "browser":
return user=new Browser(name,password,role);
case "operator":
return user=new Operator(name,password,role);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
synchronized public static Enumeration<User> getAllUser() throws SQLException{
Vector<User> vec=new Vector<User>();
User user;
String name,password,role;
try {
statement = connection.createStatement();
resultset = statement.executeQuery("select * from user_info");
while(resultset.next()){
name=resultset.getString("username");
password=resultset.getString("password");
role=resultset.getString("role");
switch(role){
case "administrator":
user=new Administrator(name,password,role);break;
case "browser":
user=new Browser(name,password,role);break;
case "operator":
user=new Operator(name,password,role);break;
default:
user=null;
}
vec.add(user);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return vec.elements();
}
synchronized public static boolean updateUser(String name, String password, String role){
try {
statement = connection.createStatement();
if((statement.executeUpdate("update user_info set password='"+password+"',role='"+role+"' where username='"+name+"'"))!=0)
return true;
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
synchronized public static boolean insertUser(String name, String password, String role){
try {
statement = connection.createStatement();
if(statement.execute("insert into user_info values('"+name+"','"+password+"','"+role+"')"))
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
synchronized public static boolean deleteUser(String name){
try {
statement = connection.createStatement();
if(statement.execute("delete from user_info where username='"+name+"'"))
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public static void disconnectFromDB() {
try {
connectedToDatabase = false;
resultset.close();
statement.close();
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
}
}
Doc.java
import java.sql.Timestamp;
class Doc{
private String ID;
private String creator;
private Timestamp timestamp;
private String description;
private String filename;
public Doc(String ID, String creator, Timestamp timestamp, String description, String filename) {
super();
this.ID = ID;
this.creator = creator;
this.timestamp = timestamp;
this.description = description;
this.filename=filename;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
}
FileManagement.java
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Enumeration;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
public class FileManageGUI {
static JFrame archivesManageFrame = new JFrame("文件管理界面") ;
static JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
static int screenWidth;
static int screenHeight;
static int frameWidth;
static int frameHeight;
static JPanel downloadPanel = new JPanel();
static JPanel uploadPanel = new JPanel();
public static void playArchivesManageGUI(int index) {
archivesManageFrame.setSize(450, 250);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = toolkit.getScreenSize();
screenWidth= dimension.width;
screenHeight = dimension.height;
frameWidth = archivesManageFrame.getWidth();
frameHeight = archivesManageFrame.getHeight();
archivesManageFrame.setLocation((screenWidth-frameWidth)/2, (screenHeight-frameHeight)/2);
tabbedPane.addTab("档案上传",uploadPanel);
tabbedPane.addTab("档案下载", downloadPanel);
String userRole = Client.get_Role();
if(userRole.equalsIgnoreCase("administrator")||userRole.equalsIgnoreCase("browser")){
tabbedPane.setEnabledAt(0, false);
}
tabbedPane.setSelectedIndex(index);
if(index == 0){
downloadPanel.removeAll();
uploadPanel.removeAll();
getUploadFileGUI();}
else if(index == 1){
downloadPanel.removeAll();
uploadPanel.removeAll();
try {
getDownloadFileGUI();
} catch (SQLException e1) {
e1.printStackTrace();
}}
tabbedPane.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e) {
int selectedIndex = tabbedPane.getSelectedIndex();
switch(selectedIndex){
case 0 :
uploadPanel.removeAll();
downloadPanel.removeAll();
getUploadFileGUI();
break;
case 1 :
uploadPanel.removeAll();
downloadPanel.removeAll();
try {
getDownloadFileGUI();
} catch (SQLException e1) {
e1.printStackTrace();
}
break;
default :
break;
}
}
});
archivesManageFrame.add(tabbedPane,BorderLayout.CENTER);
archivesManageFrame.setVisible(true);
archivesManageFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public static void getUploadFileGUI(){
JLabel archivesNumberLabel = new JLabel("档案号:");
JLabel archivesDescriptionLabel = new JLabel("档案描述:");
JLabel archivesNameLabel = new JLabel("档案文件名:");
final JTextField archivesNumberField = new JTextField(12);
final JTextArea archivesDescriptionArea = new JTextArea(4,12);
archivesDescriptionArea.setLineWrap(true);
final JTextField archivesNameField = new JTextField(12);
JButton openButton = new JButton("打开");
JButton uploadButton = new JButton("上传");
JButton cancelButton = new JButton("取消");
uploadPanel.setLayout(new GridLayout(4,3,5,5));
JPanel panel1 = new JPanel();
panel1.add(archivesNumberLabel);
uploadPanel.add(panel1);
JPanel panel2 = new JPanel();
panel2.add(archivesNumberField);
uploadPanel.add(panel2);
uploadPanel.add(new JPanel());
JPanel panel3 = new JPanel();
panel3.add(archivesDescriptionLabel);
uploadPanel.add(panel3);
JScrollPane panel4 = new JScrollPane(archivesDescriptionArea); //滚动条
uploadPanel.add(panel4);
uploadPanel.add(new JPanel());
JPanel panel5 = new JPanel();
panel5.add(archivesNameLabel);
uploadPanel.add(panel5);
JPanel panel6 = new JPanel();
panel6.add(archivesNameField);
uploadPanel.add(panel6);
JPanel panel7 = new JPanel();
panel7.add(openButton);
uploadPanel.add(panel7);
JPanel panel8 = new JPanel();
panel8.add(uploadButton);
uploadPanel.add(panel8);
uploadPanel.add(new JPanel());
JPanel panel9 = new JPanel();
panel9.add(cancelButton);
uploadPanel.add(panel9);
openButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int flag = fileChooser.showOpenDialog(uploadPanel); //弹出一个 "Open File" 文件选择器对话框
if(flag == JFileChooser.APPROVE_OPTION){
File selectedFile = fileChooser.getSelectedFile(); //返回选中的文件
archivesNameField.setText(selectedFile.getAbsolutePath());
}
}
});
uploadButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog();
dialog.setTitle("消息");
dialog.setLayout(new GridLayout(3,1,0,0));
JLabel jl = new JLabel();
jl.setText("确定上传该文件吗?");
dialog.setBounds((screenWidth-frameWidth)/2, (screenHeight-frameHeight)/2, 200, 230);
JButton confirmBotton = new JButton("确定");
JButton cancelBotton = new JButton("取消");
JPanel jp1 = new JPanel();
jp1.add(jl);
JPanel jp2 =new JPanel();
jp2.add(confirmBotton);
jp2.add(cancelBotton);
dialog.add(new JPanel());
dialog.add(jp1);
dialog.add(jp2);
dialog.setVisible(true);
confirmBotton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String archivesNumber = archivesNumberField.getText();
String archivesDescription = archivesDescriptionArea.getText();
String archivesName = archivesNameField.getText();
String uploaderName = Client.get_Name();
JDialog jdialog = new JDialog();
jdialog.setTitle("消息");
jdialog.setLayout(new GridLayout(2,1,0,0));
JLabel label = new JLabel();
jdialog.setBounds((screenWidth-frameWidth)/2, (screenHeight-frameHeight)/2, 200, 130);
JButton button = new JButton("确定");
JPanel jp1 = new JPanel();
jp1.add(label);
JPanel jp2 =new JPanel();
jp2.add(button);
jdialog.add(jp1);
jdialog.add(jp2);
// Timestamp timestamp=new Timestamp(System.currentTimeMillis());
try {
Client.Upload(archivesNumber,uploaderName,archivesDescription,archivesName,archivesManageFrame);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//
// File infile=new File(archivesName);
// File outfile=new File(LoginGUI.getUser().getUploadPath()+infile.getName());
//
//
//
// byte b[]=new byte[1024];
// try{
// boolean bl = DataProcessing.insertDoc(archivesNumber,uploaderName,timestamp,archivesDescription,infile.getName());
// if(!bl) {
//
// throw new Exception();
//
// }
//
// BufferedInputStream bis = new BufferedInputStream(new FileInputStream(infile));
// BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outfile));
//
//
// while(true){
// int inlength = bis.read(b);
// if(inlength == -1){
// break;
// }
// bos.write(b, 0, inlength);
// bos.flush();
// }
//
//
// bis.close();
// bos.close();
// label.setText("文件上传成功!");
//
// button.addActionListener(new ActionListener(){
// public void actionPerformed(ActionEvent e) {
// dialog.dispose();
// jdialog.dispose();
// }
// });;
// archivesNumberField.setText(null);
// archivesDescriptionArea.setText(null);
// archivesNameField.setText(null);
//
// }catch(Exception e1){
// label.setText("文件上传失败!");
// e1.printStackTrace();
// }
// jdialog.setVisible(true);
//
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
dialog.dispose();
jdialog.dispose();
}
});
}
});
cancelBotton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
}
});
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
downloadPanel.removeAll();
uploadPanel.removeAll();
archivesManageFrame.dispose();
}
});
}
public static void getDownloadFileGUI() throws SQLException{
Enumeration <Doc> e = DataProcessing.getAllDocs();
String []columnNames = {"档案号","创建者","时间","描述","文件名"};
String [][]tableValues = new String[100][5];
int i=0;
while(e.hasMoreElements()){
Doc doc = e.nextElement();
String number = doc.getID();
tableValues[i][0]=number;
String creator = doc.getCreator();
tableValues[i][1] = creator;
Timestamp time = doc.getTimestamp();
tableValues[i][2] = time.toString();
String description = doc.getDescription();
tableValues[i][3] = description;
String fileName = doc.getFilename();
tableValues[i][4] = fileName;
i++;
}
DefaultTableModel tableModel= new DefaultTableModel(tableValues,columnNames);
final JTable table = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(table);
JButton uploadButton = new JButton("下载");
JButton cancelButton = new JButton("取消");
downloadPanel.setLayout(new BorderLayout());
JPanel jp = new JPanel();
jp.add(uploadButton);
jp.add(cancelButton);
downloadPanel.add(BorderLayout.CENTER,scrollPane);
downloadPanel.add(BorderLayout.SOUTH,jp);
uploadButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if(row==-1){
JOptionPane.showMessageDialog(null, "请选择文件!","提示",JOptionPane.ERROR_MESSAGE);
}
else{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int flag = fileChooser.showSaveDialog(downloadPanel);
String ID = table.getValueAt(row,0).toString();
// Doc doc=null;
// doc=DataProcessing.searchDoc(ID);
//
// String directoryName= "";
// File selectedFile;
// if(flag == JFileChooser.APPROVE_OPTION){
// selectedFile = fileChooser.getSelectedFile();
// directoryName = selectedFile.getAbsolutePath();
//
//
// File uploaddir = new File(LoginGUI.getUser().getUploadPath());
// if(!uploaddir.exists()){
// uploaddir.mkdirs();
// }
//
// byte b[] = new byte[1024];
// File infile = new File(LoginGUI.getUser().getUploadPath()+doc.getFilename());
// File outfile = new File(directoryName+"\\"+infile.getName());
//
// if(!outfile.exists()){
// try {
// outfile.createNewFile();
// } catch (IOException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
// }
//
final JDialog jdialog = new JDialog();
jdialog.setTitle("提示");
jdialog.setLayout(new GridLayout(2,1,0,0));
final JLabel label = new JLabel();
jdialog.setBounds((screenWidth-frameWidth)/2+150, (screenHeight-frameHeight)/2+180, 200, 130);
JButton button = new JButton("确定");
JPanel jp1 = new JPanel();
jp1.add(label);
JPanel jp2 =new JPanel();
jp2.add(button);
jdialog.add(jp1);
jdialog.add(jp2);
try {
Client.Download(ID,archivesManageFrame);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//
// try{
// BufferedInputStream bis;
// bis = new BufferedInputStream(new FileInputStream(infile));
// BufferedOutputStream bos;
//
// bos = new BufferedOutputStream(new FileOutputStream(outfile));
// while(true){
// int inlength = bis.read(b);
// if(inlength == -1)
// break;
// bos.write(b,0, inlength);
// }
// bos.flush();
// bis.close();
// bos.close();
// label.setText("文件下载成功!");
// }catch(Exception e1){
// label.setText("文件下载失败!");
// e1.printStackTrace();
// }
// jdialog.setVisible(true);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
jdialog.dispose();
}
});
}
}
});
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
downloadPanel.removeAll();
uploadPanel.removeAll();
archivesManageFrame.dispose();
}
});
}
}
LoginGUI.java
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.sql.SQLException;
import javax.swing.*;
public class LoginGUI {
public static void systemLogin(){
JFrame loginframe = new JFrame("系统登录");
loginframe.setSize(300, 220); //设置窗口大小
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = toolkit.getScreenSize(); //获得屏幕大小
int screenWidth = dimension.width; //获得屏幕的宽度
int screenHeight = dimension.height; //获得屏幕的高度
int frameWidth = loginframe.getWidth(); //获得窗口宽度
int frameHeight = loginframe.getHeight(); //获得窗口高度
loginframe.setLocation((screenWidth-frameWidth)/2, (screenHeight-frameHeight)/2); //窗口居中显示
JPanel jp1 = new JPanel(); //创建三个容器,用于布局
JPanel jp2 = new JPanel();
JPanel jp3 = new JPanel();
JLabel nameLabel = new JLabel("用户名: "); //设置“用户名”标签
JTextField nameField = new JTextField(13); //设置用户名的输入文本框
jp1.add(nameLabel);
jp1.add(nameField);
JLabel passwordLabel = new JLabel("密 码: "); //设置“密码”标签
JPasswordField passwordField = new JPasswordField(13); //设置密码的输入文本框
jp2.add(passwordLabel);
jp2.add(passwordField);
JButton loginButton = new JButton("登录"); //设置“登录”“取消”按钮
JButton cancelButton = new JButton("取消");
jp3.add(loginButton);
jp3.add(cancelButton);
loginframe.add(new JPanel());
loginframe.add(jp1);
loginframe.add(jp2);
loginframe.add(jp3);
loginframe.add(new JPanel()); //设置五个panel,使不顶格
loginframe.setLayout(new GridLayout(5,1,5,5)); //设置布局方式:流式布局(行数、列数、组件水平间距、纵向间距)
loginframe.setVisible(true); //设置窗口可见
loginframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置关闭窗口默认值
loginButton.addActionListener(new ActionListener() { //“登录”按钮创建事件监听
@Override
public void actionPerformed(ActionEvent e) {
String loginName = nameField.getText(); //获得用户输入的“用户名”
String loginPassword = String.valueOf(passwordField.getPassword()); //获得用户输入的“密码”
try {
Client.Login(loginName, loginPassword, loginframe);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) throws Exception {
Client application;
systemLogin();
if ( args.length == 0 )
application = new Client( "127.0.0.1" );
else
application = new Client( args[ 0 ] );
application.runClient();
}
}
Main.java
import java.sql.SQLException;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
String name;
String password;
String tip_system = "档案系统";
String tip_menu = "请选择菜单:";
String tip_exit = "系统退出,谢谢使用!";
String infos = "******欢迎进入" + tip_system + "******\n\t" +
"1.登录\n\t" + "2.退出\n" +
"*************************";
Scanner in = new Scanner(System.in);
while(true){
System.out.println(infos);
System.out.println(tip_menu);
int option = in.nextInt();
switch(option){
case 1:
System.out.println("请输入用户名:");
name = in.next();
System.out.println("请输入密码:");
password = in.next();
User user = null;
user = DataProcessing.searchUser(name, password);
if(user == null){
System.out.println("请重新输入");
}
else{
user.showMenu();
}
break;
case 2:
System.out.println(tip_exit);
System.exit(0);
break;
}
}
}
}
MenuGUI.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.*;
public class MenuGUI {
public static void playMenu() {
JFrame menuframe = new JFrame();
JMenuBar menuBar = new JMenuBar(); //设置菜单栏,用来放置多个菜单
menuframe.setJMenuBar(menuBar);
JMenu userMenu = new JMenu("用户管理");
JMenu fileMenu = new JMenu("档案管理");
JMenu personMessageMenu = new JMenu("个人信息管理");
menuBar.add(userMenu);
menuBar.add(fileMenu);
menuBar.add(personMessageMenu); //设置三个菜单
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = toolkit.getScreenSize(); //获得屏幕大小
menuframe.setSize(dimension); //设置frame的大小
userMenu.add(new JMenuItem("修改用户"));
userMenu.add(new JMenuItem("删除用户"));
userMenu.add(new JMenuItem("添加用户")); //设置“用户管理”菜单的菜单项
fileMenu.add(new JMenuItem("档案上传"));
fileMenu.add(new JMenuItem("档案下载")); //设置“档案管理”菜单的菜单项
personMessageMenu.add(new JMenuItem("信息修改")); //设置“个人信息管理”菜单的菜单项
menuframe.setVisible(true);
menuframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String role = Client.get_Role();
String name = Client.get_Name();
switch(role){
case "administrator" :
menuframe.setTitle("系统管理员界面");
fileMenu.getItem(0).setEnabled(false); //设置管理员不可用的功能
break;
case "browser" :
menuframe.setTitle("档案浏览员界面");
userMenu.getItem(0).setEnabled(false);
userMenu.getItem(1).setEnabled(false);
userMenu.getItem(2).setEnabled(false);
fileMenu.getItem(0).setEnabled(false); //设置档案浏览员不可用的功能
break;
case "operator" :
menuframe.setTitle("档案录入员界面");
userMenu.getItem(0).setEnabled(false);
userMenu.getItem(1).setEnabled(false);
userMenu.getItem(2).setEnabled(false); //设置档案录入员不可用的功能
break;
default :
break;
}
userMenu.getItem(0).addActionListener(new ActionListener() { //修改用户
public void actionPerformed(ActionEvent e) {
int index = 0;
try {
UserGUI.playUserManageGUI(index);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
userMenu.getItem(1).addActionListener(new ActionListener() { //删除用户
public void actionPerformed(ActionEvent e) {
int index = 1;
try {
UserGUI.playUserManageGUI(index);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
userMenu.getItem(2).addActionListener(new ActionListener() { //添加用户
public void actionPerformed(ActionEvent e) {
int index = 2;
try {
UserGUI.playUserManageGUI(index);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
fileMenu.getItem(0).addActionListener(new ActionListener() { //档案上传
public void actionPerformed(ActionEvent e) {
int index = 0;
FileManageGUI.playArchivesManageGUI(index);
}
});
fileMenu.getItem(1).addActionListener(new ActionListener() { //档案下载
public void actionPerformed(ActionEvent e) {
int index = 1;
FileManageGUI.playArchivesManageGUI(index);
}
});
personMessageMenu.getItem(0).addActionListener(new ActionListener() { //信息修改
public void actionPerformed(ActionEvent e) {
PersonMessageGUI.playPersonMessageManageGUI();
}
});
}
}
Operator.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Scanner;
public class Operator extends User{
public Operator(String name,String password,String role) {
super(name,password,role);
}
public void uploadFile(String ID,String name,String filepath,String description) throws IOException, SQLException {
// System.out.println("上传成功!\n");
Scanner in = new Scanner(System.in);
File srcFile = new File(filepath);
String filename = srcFile.getName();
File destFile = new File(uploadpath + filename);
destFile.createNewFile();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
DataProcessing.insertDoc(ID, name, timestamp, description, filename);
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
byte[] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
public void showMenu() {
String tip_operator = "******欢迎来到档案录入菜单******\n\t" + "1.上传文件\n\t" +
"2.下载文件\n\t" + "3.文件列表\n\t" + "4.修改密码\n\t" + "5.退出\n" +
"****************************";
String tip_menu = "请选择菜单:";
Scanner in = new Scanner(System.in);
while(true){
System.out.println(tip_operator);
System.out.println(tip_menu);
int option;
option = in.nextInt();
switch(option) {
case 1:
System.out.println("上传文件");
System.out.println("请输入源文件名:");
String name;
name = in.next();
System.out.println("请输入档案号:");
String ID;
ID = in.next();
System.out.println("请输入文件路径:");
String filepath;
filepath = in.next();
System.out.println("请输入档案描述:");
String describtion;
describtion = in.next();
try {
uploadFile(ID,name,filepath,describtion);
} catch (IOException e1) {
System.out.println("文件错误");
} catch (SQLException e) {
System.out.println("数据库错误" + e.getMessage());
}
break;
case 2:
System.out.println("下载文件");
System.out.println("请输入档案号:");
String filename;
filename = in.next();
try {
downloadFile(filename);
} catch (IOException e) {
System.out.println("文件错误");
} catch (SQLException e) {
System.out.println("数据库错误" + e.getMessage());
}
break;
case 3:
try {
showFileList();
} catch (SQLException e) {
System.out.println("数据库错误" + e.getMessage());
}
break;
case 4:
System.out.println("修改密码");
System.out.println("请输入新密码:");
String password;
password = in.next();
try {
changeSelfInfo(password);
} catch (SQLException e) {
System.out.println("数据库错误" + e.getMessage());
}
break;
case 5:
exitSystem();
break;
}
}
}
}
PersonMessageGUI.java
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import javax.swing.*;
public class PersonMessageGUI {
public static void playPersonMessageManageGUI(){
JFrame personMessageManageFrame = new JFrame();
personMessageManageFrame.setTitle("个人信息管理");
personMessageManageFrame.setSize(300, 400);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = toolkit.getScreenSize();
int screenWidth= dimension.width;
int screenHeight = dimension.height;
int frameWidth = personMessageManageFrame.getWidth();
int frameHeight = personMessageManageFrame.getHeight();
personMessageManageFrame.setLocation((screenWidth-frameWidth)/2, (screenHeight-frameHeight)/2);
JPanel changePanel = new JPanel();
JLabel nameLabel = new JLabel("用户名: ");
JLabel roleLabel = new JLabel("属 性: ");
JLabel oldPasswordLabel = new JLabel("原密码: ");
JLabel newPasswordLabel = new JLabel("新密码: ");
JLabel newPasswordLabel2 = new JLabel("确认新密码");
JTextField nameField = new JTextField(13);
nameField.setText(Client.get_Name());
nameField.setEditable(false);
final JPasswordField oldPasswordField = new JPasswordField(13);
final JPasswordField newPasswordField = new JPasswordField(13);
final JPasswordField newPasswordField2 = new JPasswordField(13);
final JTextField roleField = new JTextField(13);
roleField.setText(Client.get_Role());
roleField.setEditable(false);
JButton confirmButton = new JButton("确定");
JButton cancelButton = new JButton("取消");
changePanel.setLayout(new GridLayout(6,1,5,5));
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
JPanel panel6 = new JPanel();
panel1.add(nameLabel);
panel1.add(nameField);
panel2.add(oldPasswordLabel);
panel2.add(oldPasswordField);
panel3.add(newPasswordLabel);
panel3.add(newPasswordField);
panel4.add(newPasswordLabel2);
panel4.add(newPasswordField2);
panel5.add(roleLabel);
panel5.add(roleField);
panel6.add(confirmButton);
panel6.add(cancelButton);
changePanel.add(panel1);
changePanel.add(panel2);
changePanel.add(panel3);
changePanel.add(panel4);
changePanel.add(panel5);
changePanel.add(panel6);
personMessageManageFrame.add(changePanel);
confirmButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String oldPassword = String.valueOf(oldPasswordField.getPassword());
String newPassword = String.valueOf(newPasswordField.getPassword());
String newPassword2 = String.valueOf(newPasswordField2.getPassword());
String role = roleField.getText();
try {
Client.ChangeSelfInfo(oldPassword, newPassword, newPassword2);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
// JDialog dialog = new JDialog();
// dialog.setTitle("取消");
// dialog.setLayout(new GridLayout(3,1,0,0));
// ImageIcon icon = new ImageIcon("问号.png");
// JLabel jl = new JLabel();
// jl.setIcon(icon);
// jl.setText("确定修改个人信息吗?");
//
// dialog.setBounds((screenWidth-frameWidth)/2, (screenHeight-frameHeight)/2, 200, 230);
// JButton confirmBotton = new JButton("确定");
// JButton cancelBotton = new JButton("取消");
// JPanel jp1 = new JPanel();
// jp1.add(jl);
// JPanel jp2 =new JPanel();
// jp2.add(confirmBotton);
// jp2.add(cancelBotton);
// dialog.add(new JPanel());
// dialog.add(jp1);
// dialog.add(jp2);
//
// JDialog jdialog = new JDialog();
// jdialog.setTitle("消息");
// jdialog.setLayout(new GridLayout(2,1,0,0));
// JLabel label = new JLabel();
// jdialog.setBounds((screenWidth-frameWidth)/2+150, (screenHeight-frameHeight)/2+180, 200, 130);
// JButton button = new JButton("确定");
// JPanel jp3 = new JPanel();
// jp3.add(label);
// JPanel jp4 =new JPanel();
// jp4.add(button);
// jdialog.add(jp3);
// jdialog.add(jp4);
// button.addActionListener(new ActionListener(){
// public void actionPerformed(ActionEvent e) {
// dialog.dispose();
// jdialog.dispose();
// }
// });
//
// confirmBotton.addActionListener(new ActionListener(){
// public void actionPerformed(ActionEvent e) {
//
// if(newPassword.equals(newPassword2)&&DataProcessing.updateUser(name, newPassword, role)){
// oldPasswordField.setText(null);
// newPasswordField.setText(null);
// newPasswordField2.setText(null);
// label.setText("修改个人信息成功!");
// }else
// label.setText("修改个人信息失败!");
//
// jdialog.setVisible(true);
// }
// });
//
// cancelBotton.addActionListener(new ActionListener(){
// public void actionPerformed(ActionEvent e) {
// dialog.dispose();
// }
//
// });
//
// if(DataProcessing.searchUser(name, oldPassword)!=null){
//
// dialog.setVisible(true);
// }else{
// label.setText("修改失败!原密码错误!");
// jdialog.setVisible(true);
// }
// }
//
// });
//
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
personMessageManageFrame.dispose();
}
});
personMessageManageFrame.setVisible(true);
personMessageManageFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
Server.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Timestamp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import javax.swing.SwingUtilities;
public class Server
{
private Socket connection;
private int counter = 1;
static ServerSocket server;
static User user;
public Server() throws IOException{
server = new ServerSocket( 12340, 100 );
int count=1;
while(true){
displayMessage( "Waiting for connection\n" );
Socket connection = server.accept(); // allow server to accept connection
displayMessage( "Connection " + count + " received from: " +
connection.getInetAddress().getHostName() );
new ServerThread(connection,"Thread"+count++);
}
}
class ServerThread extends Thread{
Socket connection;
String clientname;
DataOutputStream output;
DataInputStream input;
ServerThread(Socket con,String clientname) throws IOException{
connection=con;
this.clientname=clientname;
output = new DataOutputStream( connection.getOutputStream() );
output.flush();
input = new DataInputStream( connection.getInputStream() );
displayMessage( "\nGot I/O streams\n" );
start();
}
private void sendData( String message )
{
try
{
output.writeUTF( "SERVER>>> " + message );
output.flush();
displayMessage( "\nSERVER>>> " + message );
}
catch ( IOException ioException )
{
System.out.println( "\nError writing object" );
}
}
public void run() {
String message = "Connection successful";
sendData( message );
try {
do
{
message = ( String ) input.readUTF();
if(message.equals("CLIENT>>> CLIENT_LOGIN")) {
String name = input.readUTF();
String password = input.readUTF();
if(DataProcessing.searchUser(name, password) != null) {
output.writeUTF("LOGIN_TRUE");
output.flush();
String role = DataProcessing.searchUser(name, password).getRole();
output.writeUTF(role);
output.flush();
System.out.println(message);
System.out.println(name);
System.out.println(role);
System.out.println("SERVER>>> SERVER_LOGIN");
}else {
output.writeUTF("LODIN_FALSE");
output.flush();
}
}
else if(message.equals("CLIENT>>> CLIENT_SELF_MOD")) {
String name=input.readUTF();
String password=input.readUTF();
String role=input.readUTF();
System.out.println("CLIENT_SELF_MOD");
if(DataProcessing.updateUser(name,password,role) == true) {
output.writeUTF("SELFCHANGE_TRUE");
output.flush();
output.writeUTF(password);
output.flush();
System.out.println("SERVER>>> SERVER_SELF_MOD");
}
else {
output.writeUTF("SELFCHANGE_FALSE");
output.flush();
}
}
else if(message.equals("displayUser")) {
Enumeration<User> e = DataProcessing.getAllUser();
String[][] rowData=new String[50][3];
User user;
int i = 0;
while(e.hasMoreElements()) {
user = e.nextElement();
rowData[i][0]=user.getName();
rowData[i][1]=user.getPassword();
rowData[i][2]=user.getRole();
i++;
}
output.writeUTF("displayedUser");
output.flush();
output.writeInt(i);
output.flush();
for(int j=0;j<i;j++) {
output.writeUTF(rowData[j][0]);
output.flush();
output.writeUTF(rowData[j][1]);
output.flush();
output.writeUTF(rowData[j][2]);
output.flush();
}
}
else if(message.equals("displayDoc")) {
Enumeration<Doc> e=DataProcessing.getAllDocs();
String[][] rowData=new String[50][5];
Doc doc;
int i=0;
while(e.hasMoreElements()) {
doc=e.nextElement();
rowData[i][0]=doc.getID();
rowData[i][1]=doc.getCreator();
rowData[i][2]=doc.getTimestamp().toString();
rowData[i][3]=doc.getDescription();
rowData[i][4]=doc.getFilename();
i++;
}
output.writeUTF("displayedDoc");
output.flush();
output.writeInt(i);
output.flush();
for(int j=0;j<i;j++) {
output.writeUTF(rowData[j][0]);
output.flush();
output.writeUTF(rowData[j][1]);
output.flush();
output.writeUTF(rowData[j][2]);
output.flush();
if(rowData[j][3]!=null) {
output.writeUTF(rowData[j][3]);
output.flush();
}
output.writeUTF(rowData[j][4]);
output.flush();
}
}
else if(message.equals("USER_DELETE")) {
String name=input.readUTF();
if(DataProcessing.deleteUser(name)) {
output.writeUTF("DELETE_TRUE");
output.flush();
System.out.println("SERVER>>> "+name+" USER_DELETE");
}
else {
output.writeUTF("DELETE_FALSE");
output.flush();
}
}
else if(message.equals("USER_ADD")) {
String name=input.readUTF();
String password=input.readUTF();
String role=input.readUTF();
if(DataProcessing.insertUser(name, password, role)) {
output.writeUTF("ADD_TRUE");
output.flush();
System.out.println("SERVER>>> "+name+" USER_ADD");
}
else {
output.writeUTF("ADD_FALSE");
output.flush();
}
}
else if(message.equals("USER_UPDATE")) {
String name=input.readUTF();
String password=input.readUTF();
String role=input.readUTF();
if(DataProcessing.updateUser(name, password, role)) {
output.writeUTF("UPDATE_TRUE");
output.flush();
System.out.println("SERVER>>> "+name+" USER_UPDATE");
}
else {
output.writeUTF("UPDATE_FALSE");
output.flush();
}
}
else if(message.equals("UPLOAD")) {
Timestamp timestamp=new Timestamp(System.currentTimeMillis());
String ID=input.readUTF();
String Creator=input.readUTF();
String description=input.readUTF();
String filename=input.readUTF();
Long fileLength=input.readLong();
FileOutputStream fos=new FileOutputStream(new File("/Users/air/Documents/java/uploadfile/"+filename));
DataInputStream dis=new DataInputStream(connection.getInputStream());
byte[] sendBytes=new byte[1024];
int transLen=0;
System.out.println("----开始接收文件<"+filename+">,文件大小为<"+fileLength+">----");
while(true) {
int read=0;
read=input.read(sendBytes,0,sendBytes.length);
if(read<=0) break;
transLen+=read;
System.out.println("接收文件进度"+100*transLen*1.0/fileLength+"%...");
fos.write(sendBytes,0,read);
fos.flush();
if(transLen>=fileLength) break;
}
System.out.println("----接收文件<"+filename+">成功----");
if(DataProcessing.insertDoc(ID, Creator, timestamp, description, filename)){
output.writeUTF("UPLOAD_TRUE");
output.flush();
System.out.println("SERVER>>> CLIENT_FILE_UP");
}
else {
output.writeUTF("UPLOAD_FALSE");
output.flush();
}
}
else if(message.equals("DOWNLOAD")) {
String ID=input.readUTF();
output.writeUTF("SERVER>>> CLIENT_FILE_DOWN");
output.flush();
System.out.println("SERVER>>> CLIENT_FILE_DOWN");
String filename=DataProcessing.searchDoc(ID).getFilename();
output.writeUTF(filename);
output.flush();
String filepath="/Users/air/Documents/java/uploadfile/";
File file=new File(filepath+filename);
long fileLength=file.length();
output.writeLong(fileLength);
output.flush();
FileInputStream fis=new FileInputStream(file);
byte[] sendBytes=new byte[1024];
int length=0;
while((length=fis.read(sendBytes,0,sendBytes.length))>0) {
output.write(sendBytes,0,length);
output.flush();
}
}
else {
displayMessage(message);
}
} while ( !message.equals( "CLIENT>>> TERMINATE" ) );
}catch(IOException e) {
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
// void waitForConnection() throws IOException
// {
// displayMessage( "Waiting for connection\n" );
//
// displayMessage( "Connection " + counter + " received from: " +
// connection.getInetAddress().getHostName() );
// }
// private void getStreams() throws IOException
// {
//
// output = new DataOutputStream( connection.getOutputStream() );
// output.flush();
//
//
// input = new DataInputStream( connection.getInputStream() );
//
// displayMessage( "\nGot I/O streams\n" );
// }
// private void closeConnection()
// {
// displayMessage( "\nTerminating connection\n" );
//
// try
// {
// output.close();
// input.close();
// connection.close();
// }
// catch ( IOException ioException )
// {
// ioException.printStackTrace();
// }
// }
void displayMessage( String messageToDisplay )
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
System.out.println( messageToDisplay );
}
}
);
}
public static void main(String[] args) throws IOException {
Server server = new Server();
}
}
Client.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Client extends JFrame
{
static JFrame jframe;
static DataOutputStream output;
static DataInputStream input;
static String message = "";
static Socket client;
static String user_name;
static String user_password;
static String user_role;
static String[][] UserData;
static String[][] DocData;
static int row1;
static int row2;
public Client(String host)
{
super("client");
}
public void runClient() throws IOException
{
try
{
connectToServer();
getStreams();
processConnection();
}
catch ( EOFException eofException )
{
displayMessage( "\nClient terminated connection" );
}
catch ( IOException ioException )
{
ioException.printStackTrace();
}
finally
{
closeConnection();
}
}
private void connectToServer() throws IOException
{
displayMessage( "Attempting connection\n" );
client = new Socket( "localhost", 12340 );
displayMessage( "Connected to: " + client.getInetAddress().getHostName() );
}
private void getStreams() throws IOException
{
output = new DataOutputStream( client.getOutputStream() );
output.flush();
input = new DataInputStream( client.getInputStream() );
displayMessage( "\nGot I/O streams\n" );
}
private void processConnection() throws IOException
{
do
{
message = ( String ) input.readUTF();
if(message.equals("LOGIN_TRUE")) {
user_role = input.readUTF();
MenuGUI menu = new MenuGUI();
menu.playMenu();
jframe.dispose();
}
else if(message.equals("LOGIN_FALSE")) {
JOptionPane.showMessageDialog(null, "账号或密码错误","提示",JOptionPane.ERROR_MESSAGE);
}
else if(message.equals("SELFCHANGE_TRUE")) {
JOptionPane.showMessageDialog(null, "修改成功","提示",JOptionPane.ERROR_MESSAGE);
System.out.println("SELFCHANGE_SUCCESS");
}
else if(message.equals("SELFCHANGE_FALSE")) {
JOptionPane.showMessageDialog(null, "修改失败","提示",JOptionPane.ERROR_MESSAGE);
}
else if(message.equals("displayedUser")) {
int i = input.readInt();
UserData = new String[50][3];
for(int j=0; j<i; i++) {
UserData[j][0] = input.readUTF();
UserData[j][1] = input.readUTF();
UserData[j][2] = input.readUTF();
}
row1 = i;
}
else if(message.equals("diaplayedDoc")) {
int i = input.readInt();
DocData = new String[50][5];
for(int j=0; j<i; j++) {
DocData[j][0] = input.readUTF();
DocData[j][1] = input.readUTF();
DocData[j][2] = input.readUTF();
DocData[j][3] = input.readUTF();
DocData[j][4] = input.readUTF();
}
row2 = i;
}
else if(message.equals("DELETE_TRUE")) {
JOptionPane.showMessageDialog(null, "删除成功","提示",JOptionPane.ERROR_MESSAGE);
jframe.dispose();
System.out.println("DELETE_SUCCESS");
}
else if(message.equals("DELETE_FALSE")) {
JOptionPane.showMessageDialog(null, "账号错误","提示",JOptionPane.ERROR_MESSAGE);
}
else if(message.equals("ADD_TRUE")) {
JOptionPane.showMessageDialog(null, "添加成功","提示",JOptionPane.ERROR_MESSAGE);
jframe.dispose();
System.out.println("ADD_SUCCESS");
}
else if(message.equals("ADD_FALSE")) {
JOptionPane.showMessageDialog(null, "添加失败","提示",JOptionPane.ERROR_MESSAGE);
}
else if(message.equals("UPDATE_TRUE")) {
JOptionPane.showMessageDialog(null, "修改成功","提示",JOptionPane.ERROR_MESSAGE);
jframe.dispose();
System.out.print("UPDATE_SUCCESS");
}
else if(message.equals("UPDATE_FALSE")) {
JOptionPane.showMessageDialog(null, "修改失败","提示",JOptionPane.ERROR_MESSAGE);
}
else if(message.equals("UPLOAD_TRUE")) {
JOptionPane.showMessageDialog(null, "上传成功","提示",JOptionPane.ERROR_MESSAGE);
jframe.dispose();
System.out.println("UPLOAD_SUCCESS");
}
else if(message.equals("UPLOAD_FALSE")) {
JOptionPane.showMessageDialog(null, "上传失败","提示",JOptionPane.ERROR_MESSAGE);
}
else if(message.equals("SERVER>>> CLIENT_FILE_DOWN")) {
String filename = input.readUTF();
long fileLength = input.readLong();
FileOutputStream fos = new FileOutputStream("/Users/air/Documents/java/downloadfile/"+filename);
byte[] sendBytes = new byte[1024];
int length = 0;
System.out.println("----开始下载文件<"+filename+">,文件大小为<"+length+">----");
while(true) {
int read = 0;
read = input.read(sendBytes);
if(read == -1) break;
length += read;
System.out.println("下载文件进度"+ 100 * length * 1.0 / fileLength + "%...");
fos.write(sendBytes,0,read);
fos.flush();
if(length >= fileLength) break;
}
System.out.println("----下载文件<" + filename + ">成功----");
JOptionPane.showMessageDialog(null, "下载成功","提示",JOptionPane.ERROR_MESSAGE);
jframe.dispose();
}
} while ( !message.equals( "SERVER>>> TERMINATE" ) );
} // end method processConnection
// close streams and socket
static void closeConnection() throws IOException
{
displayMessage( "\nClosing connection" );
String logout = "CLIENT>>> CLIENT_LOGOUT";
output.writeUTF(logout);
output.flush();
System.out.println("CLIENT>>> CLIENT_LOGOUT");
try
{
output.close();
input.close();
client.close();
}
catch ( IOException ioException )
{
ioException.printStackTrace();
}
}
static void sendData( String message )
{
try
{
output.writeUTF( "CLIENT>>> " + message );
output.flush();
displayMessage( "\nCLIENT>>> " + message );
}
catch ( IOException ioException )
{
System.out.println( "\nError writing object" );
}
}
static void displayMessage( String messageToDisplay )
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
System.out.println( messageToDisplay );
}
}
);
}
static void Login(String name,String password,JFrame frame) throws IOException {
String login="CLIENT>>> CLIENT_LOGIN";
output.writeUTF(login);
System.out.println(login);
output.flush();
output.writeUTF(name);
user_name = name;
output.flush();
output.writeUTF(password);
user_password = password;
output.flush();
jframe = frame;
}
static void ChangeSelfInfo(String old_password,String new_password,String new_password2) throws IOException {
if(user_password.equals(old_password)) {
if(new_password.equals(new_password2)) {
String changeSelfInfo="CLIENT>>> CLIENT_SELF_MOD";
System.out.println("CLIENT>>> CLIENT_SELF_MOD");
output.writeUTF(changeSelfInfo);
output.flush();
output.writeUTF(user_name);
output.flush();
output.writeUTF(new_password);
output.flush();
output.writeUTF(user_role);
output.flush();
}
else {
JOptionPane.showMessageDialog(null, "两次输入的新密码不一致", "提示", JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(null, "密码错误", "提示", JOptionPane.ERROR_MESSAGE);
}
}
static void Display_user() throws IOException {
output.writeUTF("displayUser");
output.flush();
}
static void Display_Doc() throws IOException {
output.writeUTF("displayDoc");
output.flush();
}
static void DelUser(String del_name, JFrame frame) throws IOException {
jframe = frame;
if(del_name.equals(user_name)) {
JOptionPane.showMessageDialog(null, "删除失败", "提示", JOptionPane.ERROR_MESSAGE);
}
else {
output.writeUTF("USER_DELETE");
output.flush();
output.writeUTF(del_name);
output.flush();
System.out.println("CLIENT>>> " + del_name + "USER_DELETE");
}
}
static void UpdateUser(String name,String password,String role,JFrame frame) throws IOException {
jframe = frame;
output.writeUTF("USER_UPDATE");
output.flush();
output.writeUTF(name);
output.flush();
output.writeUTF(password);
output.flush();
output.writeUTF(role);
output.flush();
System.out.println("CLIENT>>> "+name+ "USER_UPDATE");
}
static void AddUser(String name, String password,String role,JFrame frame) throws IOException {
jframe = frame;
output.writeUTF("USER_ADD");
output.flush();
output.writeUTF(name);
output.flush();
output.writeUTF(password);
output.flush();
output.writeUTF(role);
output.flush();
System.out.println("CLIENT>>> "+name+ "USER_ADD");
}
static void Download(String ID,JFrame frame) throws IOException {
jframe=frame;
output.writeUTF("DOWNLOAD");
output.flush();
output.writeUTF(ID);
output.flush();
}
static void Upload(String ID,String Creator,String description,String filename,JFrame frame) throws IOException{
jframe=frame;
output.writeUTF("UPLOAD");
output.flush();
output.writeUTF(ID);
output.flush();
output.writeUTF(Creator);
output.flush();
output.writeUTF(description);
output.flush();
File file=new File(filename.trim());
String fileName=file.getName();
output.writeUTF(fileName);
output.flush();
long fileLength=file.length();
output.writeLong(fileLength);
output.flush();
FileInputStream fis=new FileInputStream(file);
DataOutputStream dos=new DataOutputStream(client.getOutputStream());
byte[] sendBytes=new byte[1024];
int length=0;
while((length=fis.read(sendBytes,0,sendBytes.length))>0) {
output.write(sendBytes,0,length);
output.flush();
}
System.out.println("CLIENT>>> CLIENT_FILE_UP");
}
static int get_Rows() {
return row1;
}
static int get_Rows2() {
return row2;
}
static String[][] get_Docs(){
return DocData;
}
static String[][] get_Users(){
return UserData;
}
static String get_Name() {
return user_name;
}
static String get_Role() {
return user_role;
}
}
User.java
import java.sql.SQLException;
import java.util.Enumeration;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public abstract class User {
private String name;
private String password;
private String role;
String uploadpath = "/Users/air/Documents/java/uploadfile/";
String downloadpath = "/Users/air/Documents/java/downloadfile/";
User(String name,String password,String role){
this.name=name;
this.password=password;
this.role=role;
}
public boolean changeSelfInfo(String password) throws SQLException{
if (DataProcessing.updateUser(name, password, role)){
this.password=password;
return true;
}else
return false;
}
public boolean downloadFile(String ID) throws IOException, SQLException{
// double ranValue=Math.random();
// if (ranValue>0.5)
// throw new IOException( "Error in accessing file" );
// System.out.println("下载文件... ...");
Doc doc = DataProcessing.searchDoc(ID);
if(doc == null) {
return false;
}
File srcFile = new File(uploadpath + doc.getFilename());
String filename = srcFile.getName();
File destFile = new File(downloadpath + filename);
if(!(destFile.exists())) {
destFile.createNewFile();
}
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
byte[] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
System.out.println("下载成功");
return true;
}
public void showFileList() throws SQLException{
// double ranValue=Math.random();
// if (ranValue>0.5)
// throw new SQLException( "Error in accessing file DB" );
// System.out.println("列表... ...");
Enumeration<Doc> e = DataProcessing.getAllDocs();
Doc doc;
while(e.hasMoreElements()) {
doc = e.nextElement();
System.out.println("ID:" + doc.getID() +"\t Creator:" + doc.getCreator() + "\t " + doc.getTimestamp() +
"\t Description:" + doc.getDescription() + " \t Filename:" + doc.getFilename());
}
}
public abstract void showMenu();
public void exitSystem(){
System.out.println("系统退出,谢谢使用! ");
System.exit(0);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getUploadPath() {
return uploadpath;
}
public void setUploadPath(String UploadPath) {
this.uploadpath = uploadpath;
}
public String getDownloadPath() {
return downloadpath;
}
public void setDownloadPath(String DownloadPath) {
this.downloadpath = downloadpath;
}
}
UserGUI.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
public class UserGUI {
static JFrame userManageFrame = new JFrame("用户管理界面");
static JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
static int screenWidth;
static int screenHeight;
static int frameWidth;
static int frameHeight;
static JPanel modifyPanel = new JPanel();
static JPanel deletePanel = new JPanel();
static JPanel addPanel = new JPanel();
static JLabel nameLabel = new JLabel("用户名: ");
static JLabel roleLabel = new JLabel("属 性: ");
static JLabel passwordLabel = new JLabel("密 码: ");
static String []usersName = new String[100];
static String []usersRole = new String[100];
static JTextField nameField = new JTextField(13);
static JPasswordField passwordField = new JPasswordField(13);
static JComboBox<String> nameComboBox;
static JComboBox<String> roleComboBox;
static DefaultTableModel tableModel;
static JTable table;
public static void playUserManageGUI(int index) throws SQLException{
userManageFrame.setSize(300, 400);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = toolkit.getScreenSize();
screenWidth= dimension.width;
screenHeight = dimension.height;
frameWidth = userManageFrame.getWidth();
frameHeight = userManageFrame.getHeight();
userManageFrame.setLocation((screenWidth-frameWidth)/2, (screenHeight-frameHeight)/2); //居中
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
modifyPanel = new JPanel();
deletePanel = new JPanel();
addPanel = new JPanel();
tabbedPane.addTab("修改用户",modifyPanel);
tabbedPane.addTab("删除用户", deletePanel);
tabbedPane.addTab("添加用户", addPanel);
tabbedPane.setSelectedIndex(index); //设置下拉框的默认选择项为下拉框中的第index个变量
nameField = new JTextField(13);
passwordField = new JPasswordField(13);
nameField.setText(null);
passwordField.setText(null);
userManageFrame.add(tabbedPane,BorderLayout.CENTER);
userManageFrame.setVisible(true);
userManageFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
if(index == 0){
modifyPanel.removeAll(); //清除面板上的组件
deletePanel.removeAll();
addPanel.removeAll();
getModifyUserGUI();}
else if(index == 1){
modifyPanel.removeAll();
deletePanel.removeAll();
addPanel.removeAll();
getDeleteUserGUI();}
else if(index == 2){
modifyPanel.removeAll();
deletePanel.removeAll();
addPanel.removeAll();
getAddUserGUI();
}
tabbedPane.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e) {
int selectedIndex = tabbedPane.getSelectedIndex();
switch(selectedIndex){
case 0 :
try {
modifyPanel.removeAll();
deletePanel.removeAll();
addPanel.removeAll();
getModifyUserGUI();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
case 1 :
try {
modifyPanel.removeAll();
deletePanel.removeAll();
addPanel.removeAll();
getDeleteUserGUI();
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
break;
case 2 :
try {
modifyPanel.removeAll();
deletePanel.removeAll();
addPanel.removeAll();
getAddUserGUI();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
default : break;
}
}
});
}
public static void getModifyUserGUI() throws SQLException{
setUser_Name_Role(); //获取name和role的集合,用于下拉框
nameComboBox = new JComboBox<String>(usersName);
roleComboBox = new JComboBox<String>(usersRole); //建立name、role的下拉框
nameComboBox.setPreferredSize(new Dimension(150,24));
roleComboBox.setPreferredSize(new Dimension(150,24)); //设置下拉框的宽度和高度
JPanel jp_name = new JPanel();
JLabel nameLabel = new JLabel("用户名: ");
jp_name.add(nameLabel);
jp_name.add(nameComboBox);
modifyPanel.add(jp_name); //添加用户名及其下拉框
JPanel jp_password = new JPanel();
JLabel passwordLabel = new JLabel("密 码: ");
jp_password.add(passwordLabel);
jp_password.add(passwordField);
modifyPanel.add(jp_password); //添加密码及其下拉框
JPanel jp_role = new JPanel();
JLabel roleLabel = new JLabel("属 性: ");
jp_role.add(roleLabel);
jp_role.add(roleComboBox);
modifyPanel.add(jp_role); //添加属性及其下拉框
JPanel jp_confirmandcancel = new JPanel();
JButton confirmButton = new JButton("确定");
JButton cancelButton = new JButton("取消");
jp_confirmandcancel.add(confirmButton);
jp_confirmandcancel.add(cancelButton);
modifyPanel.add(jp_confirmandcancel); //添加“确定”和“取消”按钮
modifyPanel.setLayout(new GridLayout(4,1,5,5)); //布局
confirmButton.addActionListener(new ActionListener(){ //点击“确定”按钮弹出对话框
public void actionPerformed(ActionEvent e) {
getConfirmDialog();
}
});
cancelButton.addActionListener(new ActionListener(){ //点击“取消”按钮清除该面板上的组件回到上一个面板
public void actionPerformed(ActionEvent e) {
getCancel();
}
});
}
public static void getDeleteUserGUI() throws SQLException{
setUser_Name_Role();
Enumeration<User> e = DataProcessing.getAllUser();
String []columnNames = {"用户名","密码","属性"};
String [][]tableValues = new String[100][3];
int i = Client.get_Rows();
while(e.hasMoreElements()){
User user = e.nextElement();
String userName = user.getName();
tableValues[i][0]=userName;
String userPassword = user.getPassword();
tableValues[i][1] = userPassword;
String userRole = user.getRole();
tableValues[i][2] = userRole;
i++;
}
tableModel = new DefaultTableModel(tableValues,columnNames); //建立表的模型
table = new JTable(tableModel); //建立表
JScrollPane scrollPane = new JScrollPane(table); //建表的滚动条
scrollPane.setPreferredSize(new Dimension(250, 200)); //设置滚动条的大小
JButton confirmButton = new JButton("确定");
JButton cancelButton = new JButton("取消");
deletePanel.setLayout(new BorderLayout()); //设置表和按钮的布局
JPanel jp = new JPanel();
deletePanel.add(BorderLayout.CENTER,scrollPane);
deletePanel.add(BorderLayout.SOUTH,jp);
confirmButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
getConfirmDialog();
}
});
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
getCancel();
}
});
}
public static void getAddUserGUI() throws SQLException{
setUser_Name_Role();
roleComboBox = new JComboBox<String>(usersRole);
roleComboBox.setPreferredSize(new Dimension(150,24));
JButton confirmButton = new JButton("确定");
JButton cancelButton = new JButton("取消");
addPanel.setLayout(new GridLayout(4,1,5,5));
JPanel jp1 = new JPanel();
jp1.add(nameLabel);
jp1.add(nameField);
JPanel jp2 = new JPanel();
jp2.add(passwordLabel);
jp2.add(passwordField);
JPanel jp3 = new JPanel();
jp3.add(roleLabel);
jp3.add(roleComboBox);
JPanel jp4 = new JPanel();
jp4.add(confirmButton);
jp4.add(cancelButton);
addPanel.add(jp1);
addPanel.add(jp2);
addPanel.add(jp3);
addPanel.add(jp4);
confirmButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
getConfirmDialog();
}
});
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
getCancel();
}
});
}
public static void setUser_Name_Role() throws SQLException{ //获取name和role的集合,用于下拉框
Enumeration<User> e = DataProcessing.getAllUser();
usersRole = new String[]{"administrator","operator","browser"};
usersName = new String[100];
int i=0;
while(e.hasMoreElements()){
User user = e.nextElement();
String userName = user.getName();
usersName[i] = userName;
i++;
}
}
public static void getConfirmDialog(){
JPanel jp1 = new JPanel();
JLabel jl = new JLabel(); //设置标签
jp1.add(jl);
int index = tabbedPane.getSelectedIndex();
if(index==0){
jl.setText("确定修改该用户信息吗?");
}else if(index==1){
jl.setText("确定删除该用户吗?");
}else{
jl.setText("确定添加该用户吗?");
}
JPanel jp2 =new JPanel();
JButton confirmBotton = new JButton("确定");
JButton cancelBotton = new JButton("取消"); //设置确定取消按钮
jp2.add(confirmBotton);
jp2.add(cancelBotton);
JDialog dialog = new JDialog(); //新建弹出窗口
dialog.setTitle("消息");
dialog.setBounds((screenWidth-frameWidth)/2+120, (screenHeight-frameHeight)/2+100, 200, 230);
dialog.add(new JPanel());
dialog.add(jp1);
dialog.add(jp2); //设置弹出窗口
dialog.setLayout(new GridLayout(3,1,0,0));
dialog.setVisible(true);
confirmBotton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String password = String.valueOf(passwordField.getPassword());
String role = (String) roleComboBox.getSelectedItem();
JDialog jdialog = new JDialog();
jdialog.setTitle("提示");
jdialog.setLayout(new GridLayout(2,1,0,0));
JLabel label = new JLabel();
int index = tabbedPane.getSelectedIndex();
if(index == 0){
name = (String)nameComboBox.getSelectedItem();
try {
Client.UpdateUser(name, password, role, userManageFrame);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else if(index == 1){
int row = table.getSelectedRow();
String getName = table.getValueAt(row,0).toString();
try {
Client.DelUser(getName, userManageFrame);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else{
try {
Client.AddUser(name, password, role, userManageFrame);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
jdialog.setBounds((screenWidth-frameWidth)/2, (screenHeight-frameHeight)/2, 200, 130);
JPanel jp1 = new JPanel();
JPanel jp2 =new JPanel();
jdialog.add(jp1);
jdialog.add(jp2);
jdialog.setVisible(true);
jp1.add(label);
JButton button = new JButton("确定");
jp2.add(button);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
dialog.dispose();
jdialog.dispose();
}
});
}
});
cancelBotton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
}
public static void getCancel(){
modifyPanel.removeAll();
deletePanel.removeAll();
addPanel.removeAll();
nameField.setText(null);
passwordField.setText(null);
userManageFrame.dispose();
}
}
更多推荐
已为社区贡献2条内容
所有评论(0)