[Java] 로그인 ObjectStream 활용

Jeini·2023년 2월 9일
0

📌 Code list

목록 보기
47/55
post-thumbnail

저번에 했던 로그인폼에서 ObjectStream을 활용해보았다.

package Login;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.JTextComponent;


public class LoginForm extends JFrame implements ActionListener {
	private JTextComponent tfId;
	private JTextComponent pfPw;
	
	private JButton btnLogin;
	private JButton btnJoin;
	
	private Vector<User> list;
	
	private File file = new File("user.txt");
	private boolean isUpdated = false;
	public LoginForm() {
		loadData();
		init();
		setDisplay();
		addListener();
		showFrame();
	}
    
	private void loadData() {
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = new FileInputStream(file);
			ois = new ObjectInputStream(fis);
			
			list = (Vector<User>)(ois.readObject());
			
			while(ois.available() != 0) {
				User user = new User(
					ois.readUTF(),
					ois.readUTF(),
					ois.readUTF(),
					ois.readUTF(),
					ois.readUTF()
				);
				list.add(user);
			}
		} catch(FileNotFoundException e) {
			list = new Vector<User>();
			if(file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		} catch(IOException | ClassNotFoundException e) {
			JOptionPane.showMessageDialog(
				this,
				"데이터 파일을 불러오던 도중 에러가 발생했습니다. 프로그램을 종료합니다.",
				"에러",
				JOptionPane.ERROR_MESSAGE
			);
			System.exit(0);
		} finally {
			closeAll(ois, fis);
		}
	}
	private void closeAll(Closeable... c) {
		for(Closeable temp : c) {
			try {
				temp.close();
			} catch(Exception e) {}
		}
	}
	private void init() {	
		tfId = LoginUtils.getTextComponent(LoginUtils.TEXT);
		pfPw = LoginUtils.getTextComponent(LoginUtils.PASSWORD);;		
		btnJoin = LoginUtils.getButton("Join");		
		btnLogin = LoginUtils.getButton("Login");
	}

	private void setDisplay() {		
		JPanel pnlText = new JPanel(new GridLayout(0,1));
		JPanel pnlInput = new JPanel(new GridLayout(0,1));
				
		pnlText.add(LoginUtils.getLabel("ID"));
		pnlText.add(LoginUtils.getLabel("Password"));
		
		JPanel pnlId = new JPanel();
		pnlId.add(tfId);
		JPanel pnlPw = new JPanel();
		pnlPw.add(pfPw);
		pnlInput.add(pnlId);
		pnlInput.add(pnlPw);
		
		JPanel pnlSouth = new JPanel();
		pnlSouth.add(btnLogin);
		pnlSouth.add(btnJoin);
				
		JPanel pnlMain = new JPanel(new BorderLayout());
		pnlMain.add(pnlText, BorderLayout.WEST);
		pnlMain.add(pnlInput, BorderLayout.CENTER);
		pnlMain.add(pnlSouth, BorderLayout.SOUTH);
		
		pnlMain.setBorder(new EmptyBorder(5, 10, 5, 10));
		
		add(pnlMain, BorderLayout.CENTER);
	}

	private void addListener() {
		btnLogin.addActionListener(this);
		btnJoin.addActionListener(this);
		addWindowListener(new WindowAdapter(){
			@Override
			public void windowClosing(WindowEvent we) {
				int result = JOptionPane.showConfirmDialog(
					LoginForm.this,
					"exit?",
					"question",
					JOptionPane.YES_NO_OPTION,
					JOptionPane.QUESTION_MESSAGE
				);
				if(result == JOptionPane.YES_OPTION) {
					boolean flag = true;
					if(isUpdated) {
						flag = saveData();
					} 
					if(flag) {
						System.exit(0);
					}
				}
			}
		});
	}
	
	private boolean saveData() {
		boolean flag = true;
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = new FileOutputStream(file);
			oos = new ObjectOutputStream(fos);
			
			oos.writeObject(list);
			oos.flush();
			oos.reset();
		} catch(IOException e) {
			JOptionPane.showMessageDialog(
				this,
				"데이터 저장중 에러가 발생했습니다. 잠시후 다시 시도하세요.",
				"에러",
				JOptionPane.ERROR_MESSAGE
			);
			flag = false;
		} finally {
			closeAll(oos, fos);
		}
		return flag;
	}
	private void showFrame() {
		setTitle("Login");
		pack();
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		setLocationRelativeTo(null);
		setResizable(false);
		setVisible(true);
	}	

	@Override
	public void actionPerformed(ActionEvent e) {
		Object src = e.getSource();		
		if(src == btnLogin) {
			JTextComponent input = null;
			String msg = "welcome!!";
			User user = null;
			if(LoginUtils.isEmpty(tfId)) {
				msg = "input your ID";
				input = tfId;
			} else {
				if(LoginUtils.isEmpty(pfPw)) {
					msg = "input your password";
					input = pfPw;
				} else {
					String uid = tfId.getText();
					String upw = pfPw.getText();
					user = findUser(uid);
					if( user == null ){
						msg = "check your ID";
						input = tfId;
					} else {
						if(!upw.equals(user.getUpw())) { 
							msg = "check your password";
							input = pfPw;
						}
					}
				}
			}
			JOptionPane.showMessageDialog(
				this,
				msg,
				"Information",
				JOptionPane.INFORMATION_MESSAGE	
			);
			if(input != null) {
				input.requestFocus();
			} else {
				clear();
				setVisible(false);
				new InformationForm(this, user);				
			}
		} else {			
			clear();
			setVisible(false);			
			new JoinForm(this);			
		}
	}

	private void clear() {
		tfId.setText("");
		pfPw.setText("");
	}
	
	public User findUser(String userId) {
		int idx = list.indexOf(new User(userId));
		if(idx>=0) {
			return list.get(idx);
		} else {
			return null;
		}		
	}

	public void addUser(User user) {
		if(findUser(user.getUid()) == null) {
			list.add(user);
			isUpdated = true;
		}
	}

	public void removeUser(User user) {
		list.remove(user);
		isUpdated = true;
	}
	public static void main(String[] args) {
		new LoginForm();
	}
}
profile
Fill in my own colorful colors🎨

0개의 댓글