java在線聊天項目 客戶端登陸窗口LoginDialog的註冊用戶功能
點擊下圖註冊按鈕,出現註冊用戶面板,把手機號和判斷相同的密碼添加到MySQL數據庫中
工作原理:
與單機的軟件不同,這個聊天的登錄框不能把註冊信息直接添加進數據庫
而是應當把註冊信息發送到服務器
當服務器接收到註冊信息後,在服務端把註冊信息添加進數據庫
首先,做連接數據庫的準備
連接數據庫需要一個連接數據庫的驅動包 —— mysql-connector-java-5.1.7-bin.jar
如果忘記倒入連接mysql數據庫的包,會出現java.lang.ClassNotFoundException: com.mysql.jdbc.Driver問題
下載地址:鏈接: https://pan.baidu.com/s/1geBRqqn 密碼: 8jxm
然後,把連接數據庫的語句做成工具類,方便調用
DBUtil類,負責連接已經存在的數據庫sw_database(用DBUtil.getConn()方法)
負責連接數據庫後關閉各種資源(用DBUtil.closeAll()方法)
package com.swift.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;public class DBUtil { public static Connection getConn() { Connection conn=null; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }try { String url="jdbc:mysql://localhost:3306/sw_database"; String user="root"; String password="root"; conn=DriverManager.getConnection(url, user, password); } catch (SQLException e) { e.printStackTrace(); } return conn; } public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs) { if(conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps!=null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
接著,需要把用戶註冊的信息添加進數據庫的sw_user表中
所以,再建一個工具類DBAdd,負責添加用戶註冊信息到表中(用DBAdd.add(User user)方法)
package com.swift.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class DBAdd { public static void add(User user) { String phone = user.getUsername(); String password = user.getPassword(); Connection conn = DBUtil.getConn(); PreparedStatement ps=null; try { ps = conn.prepareStatement("insert into sw_user(username,password) values(?,?)"); ps.setString(1, phone); ps.setString(2, password); int count = ps.executeUpdate(); if (count == 1) { System.out.println("用戶添加成功"); } else { System.out.println("用戶添加失敗"); } } catch (SQLException e) { e.printStackTrace(); }finally { DBUtil.closeAll(conn, ps, null); } } }
User類代碼如下:負責用戶信息的包裝
package com.swift.jdbc; public class User { private int id; private String username; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public User(int id, String username, String password) { this.id = id; this.username = username; this.password = password; } public User() { super(); } public User(String username, String password) { this.username = username; this.password = password; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + "]"; } }
接著,在LoginDialog登陸窗口“註冊用戶”按鈕添加監聽,當點擊按鈕則把信息發送給服務端
信息發給服務端,需要建立與服務端的連接,及關閉窗口斷開連接
連接後分別發送電話號碼和驗證好的密碼
具體代碼如下:
package com.swift.frame; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ConnectException; import java.net.Socket; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.TitledBorder; import com.swift.jdbc.DBAdd; import com.swift.jdbc.DBUtil; import com.swift.jdbc.User; import com.swift.util.Center; public class LoginDialog extends JDialog { private JPasswordField passwordField_2; private JPasswordField passwordField_1; private JTextField textField_2; private JTextField textField; Socket s; DataOutputStream dos; DataInputStream dis; public static void main(String args[]) { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); try { UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { e1.printStackTrace(); } EventQueue.invokeLater(new Runnable() { public void run() { try { LoginDialog dialog = new LoginDialog(); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public LoginDialog() { super(); setResizable(false); setTitle("在線聊天登錄框"); getContentPane().setLayout(null); setBounds(100, 100, 427, 301);// 註冊時高度為578,不註冊是301 // 設置窗口居中 this.setLocation(Center.getPoint(this.getSize())); final JButton button_1 = new JButton(); button_1.setText("登錄"); button_1.setBounds(230, 222, 106, 36); getContentPane().add(button_1); final JTextField textField_1 = new JTextField(); textField_1.setBounds(148, 90, 192, 42); getContentPane().add(textField_1); final JLabel label = new JLabel(); label.setText("帳 號"); label.setBounds(76, 102, 66, 18); getContentPane().add(label); final JLabel label_1 = new JLabel(); label_1.setText("密 碼"); label_1.setBounds(76, 167, 66, 18); getContentPane().add(label_1); final JPasswordField passwordField = new JPasswordField(); passwordField.setBounds(148, 155, 192, 42); getContentPane().add(passwordField); final JButton button = new JButton(); button.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { if (LoginDialog.this.getHeight() == 301) { LoginDialog.this.setSize(427, 578); } else { LoginDialog.this.setSize(427, 301); } // 設置窗口不斷居中 LoginDialog.this.setLocation(Center.getPoint(LoginDialog.this.getSize())); } }); button.setText("註冊"); button.setBounds(76, 222, 106, 36); getContentPane().add(button); final JPanel panel = new JPanel(); panel.setLayout(null); panel.setBorder(new TitledBorder(null, "註冊用戶", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); panel.setBounds(10, 278, 401, 226); getContentPane().add(panel); final JLabel label_2 = new JLabel(); label_2.setBounds(44, 41, 65, 18); label_2.setText("手機號:"); panel.add(label_2); textField = new JTextField(); textField.setBounds(115, 35, 225, 30); panel.add(textField); final JButton button_2 = new JButton(); button_2.setText("發送驗證"); button_2.setBounds(243, 75, 97, 30); panel.add(button_2); textField_2 = new JTextField(); textField_2.setBounds(115, 104, 95, 30); panel.add(textField_2); final JLabel label_3 = new JLabel(); label_3.setText("驗證碼:"); label_3.setBounds(44, 110, 65, 18); panel.add(label_3); passwordField_1 = new JPasswordField(); passwordField_1.setBounds(115, 143, 231, 30); panel.add(passwordField_1); passwordField_2 = new JPasswordField(); passwordField_2.setBounds(115, 175, 231, 30); panel.add(passwordField_2); final JLabel label_4 = new JLabel(); label_4.setText("密 碼:"); label_4.setBounds(44, 149, 65, 18); panel.add(label_4); final JLabel label_5 = new JLabel(); label_5.setText("驗證密碼:"); label_5.setBounds(44, 181, 65, 18); panel.add(label_5); final JButton button_3 = new JButton(); button_3.setBounds(47, 510, 97, 30); getContentPane().add(button_3); button_3.setText("放棄"); final JButton button_4 = new JButton(); button_4.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { String phone = textField.getText(); String password = null; String str1=new String(passwordField_1.getPassword()).trim(); String str2=new String(passwordField_2.getPassword()).trim(); if (str1.equals(str2)) { password = new String(passwordField_2.getPassword()).trim(); } else { System.out.println("輸入密碼不一致..."); System.exit(0); } try { dos.writeUTF(phone); dos.writeUTF(password); } catch (IOException e1) { e1.printStackTrace(); } } }); button_4.setBounds(262, 510, 97, 30); getContentPane().add(button_4); button_4.setText("註冊用戶"); connect(); this.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { disconnect(); } }); } public void connect() { try { s = new Socket("127.0.0.1", 8888); System.out.println("一個客戶端登陸中....!"); dos = new DataOutputStream(s.getOutputStream()); dis = new DataInputStream(s.getInputStream()); } catch (ConnectException e) { System.out.println("服務端異常........."); System.out.println("請確認服務端是否開啟........."); } catch (IOException e) { e.printStackTrace(); } } public void disconnect() { try { if (dos != null) dos.close(); if (s != null) s.close(); } catch (IOException e) { e.printStackTrace(); } } }
服務端要接受客戶端登陸窗發來的手機號碼和密碼
然後將信息打包成User,通過DBAdd.add(user)添加進數據庫
建立一個LoginServer類,負責接收信息和添加進數據庫
具體代碼如下:
package com.swift; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.net.BindException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import com.swift.jdbc.DBAdd; import com.swift.jdbc.User; public class LoginServer { boolean started = false; ServerSocket ss = null; Socket s = null; public static void main(String[] args) { new LoginServer().fun(); } private void fun() { try { ss = new ServerSocket(8888); started = true; } catch (BindException e) { System.out.println("端口使用中......"); } catch (IOException e1) { e1.printStackTrace(); } try { while (started) { s = ss.accept(); System.out.println("a client connected success"); Client c = new Client(s); new Thread(c).start(); } } catch (EOFException e) { System.out.println("client has closed."); } catch (Exception e) { e.printStackTrace(); } finally { try { ss.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class Client implements Runnable { private Socket s; private DataInputStream dis; private DataOutputStream dos; private boolean connected = false; public Client(Socket s) { this.s = s; try { this.dis = new DataInputStream(s.getInputStream()); this.dos = new DataOutputStream(s.getOutputStream()); connected = true; } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { try {//註意:要包括while循環,如果try在while循環裏,則出現socket closed異常 while (connected) { String phone = dis.readUTF(); String password = dis.readUTF(); System.out.println(phone); System.out.println(password); User user=new User(phone,password); DBAdd.add(user); } } catch(SocketException e) { System.out.println("一個登陸窗已經關閉...."); } catch (IOException e) { e.printStackTrace(); } finally { if (s != null) { try { s.close(); } catch (IOException e) { e.printStackTrace(); } } if (dis != null) { try { dis.close(); } catch (IOException e) { e.printStackTrace(); } } if(dos!=null) { try { dos.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }
效果圖:
打開多個登陸窗口,分別註冊用戶後關閉,服務端提示信息如下:
java在線聊天項目 客戶端登陸窗口LoginDialog的註冊用戶功能