基于Java JFrame 和Mysql的用户登录界面和用户注册界面

在学校完成Java课程设计——宾馆客房管理系统的用户登录界面

基于Java JFrame 和Mysql的用户登录界面和用户注册界面_第1张图片基于Java JFrame 和Mysql的用户登录界面和用户注册界面_第2张图片

基于Java JFrame 和Mysql的用户登录界面和用户注册界面_第3张图片

代码实现

用户类:

package com.dao;


public class User {
    private String username;
    private String password;
    public static String authority;
    
    public User(){}

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

	public static String getAuthority() {
		return authority;
	}

	public static void setAuthority(String authority) {
		User.authority = authority;
	}

	
    
    
}

功能接口:

package com.dao;


public interface UserDao {

    /**
     * 这是用户登录功能
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录是否成功
     */
    public abstract boolean login(String username, String password);

    /**
     * 这是用户注册功能
     *
     * @param user 被注册的用户信息
     */
    public abstract void regist(User user);
}

接口实现类:

package com.dao.impl;

import com.dao.UserDao;

import java.sql.*;

import com.Mysql.DatabaseConnection;
import com.dao.User;


public class UserDaoImpl implements UserDao {




    @Override
    public boolean login(String username, String password) {
        boolean flag = false;
       

        DatabaseConnection conn =new DatabaseConnection();
		Connection hcon=conn.getConnection();
                
		
		try {
			Statement sql=hcon.createStatement();
                        ResultSet rs=sql.executeQuery("select * from 用户权限表");
                        while(rs.next()){
                       	
                            if(username.equals(rs.getString(1)) && password.equals(rs.getString(2))){
                                flag=true;
                                User.setAuthority(rs.getString(3));
                                break;
                            }
                        }
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		conn.close();
		
        return flag;
    }

    @Override
    public void regist(User user) {
       DatabaseConnection conn =new DatabaseConnection();
		Connection hcon=conn.getConnection();
		String sql="insert into 用户权限表(user,password,authority) values (?,?,?)";
		try {
			
			PreparedStatement ps=hcon.prepareStatement(sql);
			
			ps.setObject(1,user.getUsername() );
                        ps.setObject(2,user.getPassword() );
                        ps.setObject(3,"staff");
			ps.execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		conn.close();
    }
}

登录界面类(入口):

package com.view;


import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JOptionPane;


@SuppressWarnings("serial")
public class Login extends javax.swing.JFrame {

   
    public Login() {
        initComponents();
         init();
    }
    
     private void init() {
        this.setTitle("登录界面");
        this.setResizable(false);
         Toolkit tk = Toolkit.getDefaultToolkit();

        //获取屏幕的宽和高
        Dimension d = tk.getScreenSize();
        double srceenWidth = d.getWidth();
        double srceenHeigth = d.getHeight();

        //获取窗体的宽和高
        int frameWidth = this.getWidth();
        int frameHeight = this.getHeight();

        //获取新的宽和高
        int width = (int) (srceenWidth - frameWidth) / 2;
        int height = (int) (srceenHeigth - frameHeight) / 2;

        //设置窗体坐标
        this.setLocation(width, height);
        //根据路径获取图片
        Image i = tk.getImage("src\\com\\view\\resource\\user.jpg");

        //给窗体设置图片
        this.setIconImage(i);
    
    }
                        
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        username = new javax.swing.JTextField();
        password = new javax.swing.JTextField();
        mainPicture = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("注册");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText("重置");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("楷体", 0, 18)); // NOI18N
        jLabel1.setText("用户名");

        jLabel2.setFont(new java.awt.Font("楷体", 0, 18)); // NOI18N
        jLabel2.setText("密  码");

        username.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                usernameActionPerformed(evt);
            }
        });

        mainPicture.setFont(new java.awt.Font("黑体", 1, 36)); // NOI18N
        mainPicture.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/view/resource/user.jpg"))); // NOI18N
        mainPicture.setText("宾馆客房管理系统");

        jButton2.setText("登陆");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPicture, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(54, 54, 54)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3)
                        .addGap(37, 37, 37)
                        .addComponent(jButton2)
                        .addGap(72, 72, 72))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(password, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)
                            .addComponent(username))
                        .addContainerGap(38, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(mainPicture, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(56, 56, 56)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(44, 44, 44))
        );

        pack();
    }                     

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    	UserRegister ur = new UserRegister();
        ur.setVisible(true);
        this.dispose();
    }                                        

    private void usernameActionPerformed(java.awt.event.ActionEvent evt) {                                         
        
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
         this.username.setText("");
         this.password.setText("");
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
              /*
        思路:
        A:获取用户名和密码
        B:正则表达式校验用户名和密码
        C:创建对象调用功能,返回一个boolean值
        D:根据boolean值给出提示
        */
          //获取用户名和密码
        String username1 = this.username.getText().trim();
        String password1 = this.password.getText().trim();
        
        //用正则表达式做数据校验
        //定义规则
        //用户名规则
        String usernameRegex = "[a-zA-z]{5}";
        //密码规则
        String passwordRegex = "\\w{6,12}";
        
        //校验
        if(!username1.matches(usernameRegex)) {
            JOptionPane.showMessageDialog(this, "用户名不满足条件(5个英文字母组成)");
            this.username.setText("");
            this.username.requestFocus();
            return;
        }
        
         if(!password1.matches(passwordRegex)) {
            JOptionPane.showMessageDialog(this, "密码不满足条件(6-12个任意单词字符)");
            this.password.setText("");
            this.password.requestFocus();
            return;
        }
         
         //创建对象调用功能,返回一个boolean值
         com.dao.UserDao ud = new com.dao.impl.UserDaoImpl();
         boolean flag =  ud.login(username1, password1);

         
         if(flag){
              JOptionPane.showMessageDialog(this, "恭喜你登录成功");          
              com.jframe.Homepage h = new com.jframe.Homepage();
              h.setVisible(true);
              this.dispose();
     
             
         }else {
               JOptionPane.showMessageDialog(this, "用户名或者密码有误");
               this.username.setText("");
               this.password.setText("");
               this.username.requestFocus();
         }
    }                                        

    
    public static void main(String args[]) {
    
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
    
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Login().setVisible(true);
            }
        });
    }
          
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel mainPicture;
    private javax.swing.JTextField password;
    private javax.swing.JTextField username;
              
}

注册界面类:

package com.view;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JOptionPane;


@SuppressWarnings("serial")
public class UserRegister extends javax.swing.JFrame {

  
    public UserRegister() {
        initComponents();
        init();
    }

     private void init() {
        this.setTitle("注册界面");
        this.setResizable(false);
         Toolkit tk = Toolkit.getDefaultToolkit();

        //获取屏幕的宽和高
        Dimension d = tk.getScreenSize();
        double srceenWidth = d.getWidth();
        double srceenHeigth = d.getHeight();

        //获取窗体的宽和高
        int frameWidth = this.getWidth();
        int frameHeight = this.getHeight();

        //获取新的宽和高
        int width = (int) (srceenWidth - frameWidth) / 2;
        int height = (int) (srceenHeigth - frameHeight) / 2;

        //设置窗体坐标
        this.setLocation(width, height);
        //根据路径获取图片
        Image i = tk.getImage("src\\com\\view\\resource\\user.jpg");

        //给窗体设置图片
        this.setIconImage(i);
    
    }
                        
    private void initComponents() {

        password = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        username = new javax.swing.JTextField();
        mainPicture1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton4.setText("确认");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton6.setText("取消");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("楷体", 0, 18)); // NOI18N
        jLabel5.setText("用户名");

        jLabel6.setFont(new java.awt.Font("楷体", 0, 18)); // NOI18N
        jLabel6.setText("密  码");

        username.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                usernameActionPerformed(evt);
            }
        });

        mainPicture1.setFont(new java.awt.Font("黑体", 1, 36)); // NOI18N
        mainPicture1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/view/resource/user.jpg"))); // NOI18N
        mainPicture1.setText("宾馆客房管理系统");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(54, 54, 54)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel6))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(password, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)
                                    .addComponent(username)))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGap(98, 98, 98)
                                .addComponent(jButton4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 80, Short.MAX_VALUE)
                                .addComponent(jButton6)
                                .addGap(45, 45, 45)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(mainPicture1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(mainPicture1, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(56, 56, 56)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton6)
                    .addComponent(jButton4))
                .addGap(44, 44, 44))
        );

        pack();
    }//                         

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        /*
        分析:
        A:获取用户名和密码
        B:用正则表达式做数据校验
        C:封装成用户对象
        D:调用用户操作的功能进行注册
        E:回到登录界面
        */
        //获取用户名和密码
        String username1 = this.username.getText().trim();
        String password1 = this.password.getText().trim();

        //用正则表达式做数据校验
        //定义规则
        //用户名规则
        String usernameRegex = "[a-zA-z]{5}";
        //密码规则
        String passwordRegex = "\\w{6,12}";

        //校验
        if(!username1.matches(usernameRegex)) {
            JOptionPane.showMessageDialog(this, "用户名不满足条件(5个英文字母组成)");
            this.username.setText("");
            this.username.requestFocus();
            return;
        }

        if(!password1.matches(passwordRegex)) {
            JOptionPane.showMessageDialog(this, "密码不满足条件(6-12个任意单词字符)");
            this.password.setText("");
            this.password.requestFocus();
            return;
        }

        //封装成用户对象
        com.dao.User user = new com.dao.User();
        user.setUsername(username1);
        user.setPassword(password1);

        //调用用户操作的功能进行注册
        com.dao.UserDao ud = new com.dao.impl.UserDaoImpl();
        ud.regist(user);

        //给出提示
        JOptionPane.showMessageDialog(this, "用户注册成功,回到登录界面");

        goLogin();
    }                                        

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        goLogin();
    }                                        

    private void usernameActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        
     
    private void goLogin() {
        Login hf = new Login();
       hf.setVisible(true);
       this.dispose();
    }
   
                   
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel mainPicture1;
    private javax.swing.JTextField password;
    private javax.swing.JTextField username;
                 
}

数据库连接类:

package com.Mysql;
import java.sql.*;
public class DatabaseConnection {

	
		private static final String DBDRIVER = "com.mysql.jdbc.Driver" ;
		private static final String DBURL = "jdbc:mysql://localhost:3306/hotal?useUnicode=true&characterEncoding=utf8" ;
		private static final String DBUSER = "root" ;
		private static final String PASSWORD = "123456789" ;
		private Connection conn = null ;
		/**
		 * 在构造方法调用时将进行数据库连接对象的取得
		 */
		public DatabaseConnection() {
			try {
				Class.forName(DBDRIVER) ;	// 加载数据库驱动程序
				this.conn = DriverManager.getConnection(DBURL, DBUSER,PASSWORD) ;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		/**
		 * 取得数据库连接对象
		 * @return 实例化的Connection对象,如果返回null,表示没有连接成功
		 */
		public Connection getConnection() {
			return this.conn ;
		}
		/**
		 * 进行数据库的关闭操作
		 */
		public void close() {
			if (this.conn != null) {
				try {
					this.conn.close();
				} catch (SQLException e) {
					e.printStackTrace(); 
				}
			}
		}
}

你可能感兴趣的:(Java,Mysql,用户登录界面)