java之用户管理权限

工具:
myeclipse
数据库:
view
表格:
ceshi2


注:
建立一个java project
文件夹:com
子文件夹:dao,db,frame, util

Java内容管理员 java管理员登录界面_SQL

1: 文件夹dao下的UserDao.java

package com.dao;

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

import com.db.DbTools;
import com.util.Users;

/**
 * 
 * @author jiajikang 创建操作数据库的实现类UserDao , 在该类中定义了实现用户登录,判断权限,用户注册等的方法
 */
public class UserDao {

    // 查询用户信息
    public List<Users> selectAll() {
        // 生成查询用户信息的SQL语句
        String sql = "select * from ceshi2";
        // 创建加载连接数据库的对象
        DbTools db = new DbTools();
        // 创建Connection对象
        Connection conn = db.getConn();
        // 创建一个集合
        List<Users> ls = new ArrayList<Users>();
        try {

            Statement st = conn.createStatement();
            // 执行查询语句
            ResultSet rs = st.executeQuery(sql);
            // 遍历结果集
            while (rs.next()) {
                // 判断是否是管理员
                if (rs.getInt(4) != 1) {
                    // 创建用户信息的实体类对象
                    Users us = new Users();
                    // 为id赋值
                    us.setId(rs.getInt(1));
                    // 为用户名赋值
                    us.setUsername(rs.getString(2));
                    // 为用户密码赋值
                    us.setPassword(rs.getString(3));
                    // 为权限赋值
                    us.setPopedom(rs.getString(4));
                    // 把用户对象添加到集合中
                    ls.add(us);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 返回集合
        return ls;
    }

    /*
     * 用户登录
     */

    public int loginuser(String name, String pwd) {
        // 生成SQL语句
        String sql = "select popedom from ceshi2 where username='" + name
                + "' and password='" + pwd + "'";
        DbTools db = new DbTools();
        Connection conn = db.getConn();
        try {
            Statement st = conn.createStatement();
            // 执行SQL语句
            ResultSet rs = st.executeQuery(sql);
            // 判断集合级是否有值
            if (rs.next()) {
                // 判断登录用户的权限值是否为1
                if (rs.getInt(1) == 1) {
                    // 1 表示的权限为管理员
                    return 1;
                } else {
                    // 2 表示的权限为普通用户
                    return 2;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 3 表示无此用户
        return 3;
    }

    /*
     * 用户注册
     */
    public void addUser(String name, String pwd) {
        // 生成添加的SQL语句
        String sql = "insert into ceshi2 (username,password)values('" + name
                + "','" + pwd + "')";
        DbTools db = new DbTools();
        Connection conn = db.getConn();
        try {
            Statement st = conn.createStatement();
            // 执行SQL语句
            st.executeUpdate(sql);
            // 关闭Connection对象
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /*
     * 删除用户
     */

    public void deleteUser(int id) {
        // 生成SQL语句
        String sql = "delete from ceshi2 where id=" + id;
        DbTools db = new DbTools();
        Connection conn = db.getConn();
        ResultSet rs = null;
        try {
            Statement st = conn.createStatement();
            st.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

2: 文件夹db下的DbTools.java

package com.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 
 * @author jiajikang 操作数据库连接的类
 */
public class DbTools {
    // 定义Connection接口对象
    Connection conn;

    // 获取数据库连接方法
    public Connection getConn() {
        try {

            // 加载数据库驱动
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/view?useUnicode=true&characterEncoding=utf-8&useSSL=false";
            // 数据库用户名
            String user = "root";
            // 数据库密码
            String password = "123456";
            // 建立数据库连接,获得连接对象conn
            conn = DriverManager.getConnection(url, user, password);
            if (conn != null) {// 如果connection实例不为空
                System.out.println("数据库连接成功");

            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 返回连接信息
        return conn;
    }

}

3: 文件夹frame下
a:AddFrame.java

package com.frame;

import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;

import com.dao.UserDao;
import com.db.DbTools;
/**
 * 
 * @author jiajikang
 * 功能:单击登录窗体中 的"注册"页面,弹出注册窗体函数功能
 *
 */
public class AddFrame extends JFrame{

    private static final long serialVersionUID = -7774133711807576073L;
    private JPanel contentPane;
    private JTextField textField;
    private JPasswordField pwd1;
    private JPasswordField pwd2;

    /**
     * 启动应用程序。
     */

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AddFrame frame = new AddFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 创建框架
     */
    public AddFrame() {
        setTitle("\u65B0\u7528\u6237\u6CE8\u518C");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 311, 219);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new GridLayout(4, 1, 5, 5));

        JPanel panel1 = new JPanel();
        FlowLayout flowLayout = (FlowLayout) panel1.getLayout();
        flowLayout.setAlignment(FlowLayout.LEFT);
        contentPane.add(panel1);

        JLabel label1 = new JLabel("\u7528  \u6237  \u540D\uFF1A");
        panel1.add(label1);

        textField = new JTextField();
        panel1.add(textField);
        textField.setColumns(15);

        JPanel panel2 = new JPanel();
        FlowLayout flowLayout_1 = (FlowLayout) panel2.getLayout();
        flowLayout_1.setAlignment(FlowLayout.LEFT);
        contentPane.add(panel2);

        JLabel label2 = new JLabel("\u8F93\u5165\u5BC6\u7801\uFF1A");
        panel2.add(label2);

        pwd1 = new JPasswordField();
        pwd1.setColumns(18);
        panel2.add(pwd1);

        JPanel panel3 = new JPanel();
        FlowLayout flowLayout_2 = (FlowLayout) panel3.getLayout();
        flowLayout_2.setAlignment(FlowLayout.LEFT);
        contentPane.add(panel3);

        JLabel label3 = new JLabel("\u786E\u8BA4\u5BC6\u7801\uFF1A");
        panel3.add(label3);

        pwd2 = new JPasswordField();
        pwd2.setColumns(18);
        panel3.add(pwd2);

        JPanel panel4 = new JPanel();
        contentPane.add(panel4);

        JButton button2 = new JButton("\u63D0\u4EA4");
        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_button2_actionPerformed(e);
            }
        });
        panel4.add(button2);

        JButton button3 = new JButton("\u8FD4\u56DE");
        button3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_button3_actionPerformed(e);
            }
        });
        panel4.add(button3);
    }

    // "注册窗体"
    protected void do_button2_actionPerformed(ActionEvent e) {// "提交"按钮事件
        // 生成SQL语句
        String sql = "select * from ceshi2 where username = '" +textField.getText()+ "';";
        DbTools db=new DbTools();
        Connection conn=db.getConn();
        ResultSet rs= null;
        try {
            Statement st=conn.createStatement();
            // 执行SQL语句
            rs=st.executeQuery(sql);
            // 判断用户名是否可用
            if (!rs.next()) {
                // 判断两次密码是否一致
                if(pwd1.getText().equals(pwd2.getText())){
                    UserDao dao=new UserDao();
                    // 调用添加用户方法
                    dao.addUser(textField.getText(), pwd1.getText());
                    JOptionPane.showMessageDialog(this, "注册成功!", null, JOptionPane.INFORMATION_MESSAGE);
                    // 将注册窗体隐藏
                    this.setVisible(false);
                    RegistDemo r=new RegistDemo();
                    // 将登录窗体设置为可见
                    r.setVisible(true);
                }else{
                    // 提示两次密码不一致
                    JOptionPane.showMessageDialog(this, "两次密码不一致!", null, JOptionPane.INFORMATION_MESSAGE);
                    return;
                }
            } else {
                // 提示用户名冲突
                JOptionPane.showMessageDialog(this, "用户名冲突!", null, JOptionPane.INFORMATION_MESSAGE);
                return;
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    }

    // 注册 
    protected void do_button3_actionPerformed(ActionEvent e) {
        // 将登录窗体隐藏
        this.setVisible(false);
        RegistDemo r=new RegistDemo();
        // 将注册窗体设置为可见
        r.setVisible(true);
    }


}

b:RegistDemo.java

package com.frame;


import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;

import com.dao.UserDao;
import com.util.UserUtil;
/**
* 
* @author jiajikang
* 创建登录窗体类。RegistDemo
*
*/


public class RegistDemo extends JFrame {

   /**
    * 
    */
    //serialVersionUID类似于java类的身份证。主要用于版本控制。
   private static final long serialVersionUID = -7774133711807576073L;
   private JPanel contentPane;
   private JTextField uname;
   private JPasswordField pwd1;

   /**
    * Launch the application.
    */
   public static void main(String[] args) {
       try {
           UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
       } catch (Throwable e) {
           e.printStackTrace();
       }
       EventQueue.invokeLater(new Runnable() {
           public void run() {
               try {
                   RegistDemo frame = new RegistDemo();
                   frame.setVisible(true);
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
       });
   }

   /**
    *  创建框架。
    */
   public RegistDemo() {
       setTitle("\u7528\u6237\u767B\u5F55");
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setBounds(100, 100, 311, 189);
       contentPane = new JPanel();
       contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
       setContentPane(contentPane);
       contentPane.setLayout(new GridLayout(4, 1, 5, 5));

       JPanel panel = new JPanel();
       contentPane.add(panel);

       JLabel lblmrmrsoft = new JLabel("\u7BA1\u7406\u5458\u8D26\u53F7\uFF1Amr \u5BC6\u7801\uFF1Amrsoft");
       panel.add(lblmrmrsoft);

       JPanel panel1 = new JPanel();
       FlowLayout flowLayout = (FlowLayout) panel1.getLayout();
       flowLayout.setAlignment(FlowLayout.LEFT);
       contentPane.add(panel1);

       JLabel label1 = new JLabel("\u7528  \u6237  \u540D\uFF1A");
       panel1.add(label1);

       uname = new JTextField();
       panel1.add(uname);
       uname.setColumns(18);

       JPanel panel2 = new JPanel();
       FlowLayout flowLayout_1 = (FlowLayout) panel2.getLayout();
       flowLayout_1.setAlignment(FlowLayout.LEFT);
       contentPane.add(panel2);

       JLabel label2 = new JLabel("\u5BC6      \u7801\uFF1A");
       panel2.add(label2);

       pwd1 = new JPasswordField();
       pwd1.setColumns(18);
       panel2.add(pwd1);

       JPanel panel4 = new JPanel();
       contentPane.add(panel4);

       JButton button2 = new JButton("\u767B\u5F55");
       button2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            do_button2_actionPerformed(e);
        }
       });

       panel4.add(button2);

       JButton button3 = new JButton("\u6CE8\u518C");
       button3.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            do_button3_actionPerformed(e);
        }
       });
       panel4.add(button3);
   }

   /**
    * 
    * @param e
    * 登录按钮
    * 注册按钮
    */

   /*
    * "登录"按钮事件 
    */

    protected void do_button2_actionPerformed(ActionEvent e) {
        // 创建UserDao对象
        UserDao dao=new UserDao();
        // 调用用户登录方法
        int i=dao.loginuser(uname.getText(), pwd1.getText());
        // 判断是否有此用户
        if(i==3){
            JOptionPane.showMessageDialog(this, "登录失败", "",
                    JOptionPane.WARNING_MESSAGE);
            return;
        }else{
            UserUtil u=new UserUtil();
            // 传递该用户的权限
            u.setPopedom(i);
            SelectFrame sf=new SelectFrame();
            // 将查看用户窗体设置为可见
            sf.setVisible(true);
            // 将登录窗体隐藏
            this.setVisible(false);
        }
    }

    /*
     * "注册"按钮事件
     */
    protected void do_button3_actionPerformed(ActionEvent e) {
        AddFrame add=new AddFrame();
        // 将注册窗体设置为可见
        add.setVisible(true);
        // 将登录窗体隐藏
        this.setVisible(false);
    }
}

c: SelectFrame.java

package com.frame;

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

import com.dao.UserDao;
import com.util.UserUtil;
import com.util.Users;

public class SelectFrame extends JFrame {

    private JPanel contentPane;
    private JTable table;
    JScrollPane scrollPane = new JScrollPane();
    private DefaultTableModel defaultModel;
    UserDao dao = new UserDao();

    /**
     * 启动应用程序。
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    SelectFrame frame = new SelectFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 创建框架
     */
    public SelectFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 271, 287);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JPanel panel = new JPanel();
        panel.setBounds(0, 0, 265, 258);
        contentPane.add(panel);
        panel.setLayout(null);

        JLabel messageLabel = new JLabel("\u7528\u6237\u4FE1\u606F");
        messageLabel.setFont(new Font("华文中宋", Font.PLAIN, 16));
        messageLabel.setBounds(98, 10, 108, 34);
        panel.add(messageLabel);

        scrollPane.setBounds(21, 54, 222, 155);
        panel.add(scrollPane);

        selecttable();

        if (UserUtil.getNumber() == 1) {// 判断用户是否是管理员
        // 创建删除按钮
            JButton deleteButton = new JButton("删除");
            deleteButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    // 调用删除按钮
                    do_deleteButton_actionPerformed(arg0);
                }
            });
            deleteButton.setBounds(63, 219, 73, 23);
            panel.add(deleteButton);
        }
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                do_button_1_actionPerformed(arg0);
            }
        });
        closeButton.setBounds(154, 219, 73, 23);
        panel.add(closeButton);
    }

    public void selecttable() {
        table = new JTable();

        defaultModel = (DefaultTableModel) table.getModel();// 获得表格模型
        defaultModel.setRowCount(0);// 清空表格模型中的数据

        defaultModel.setColumnIdentifiers(new Object[] { "id", "用户名", "密码" });// 定义表头

        table.getTableHeader().setReorderingAllowed(false);
        table.setModel(defaultModel);// 设置表格模型
        List<Users> list = dao.selectAll();
        for (int i = 0; i < list.size(); i++) {
            Users us = (Users) list.get(i);
            defaultModel.addRow(new Object[] { us.getId(), us.getUsername(),
                    us.getPassword() });
        }
        scrollPane.setViewportView(table);
    }

    // 删除按钮的单击事件
    protected void do_deleteButton_actionPerformed(ActionEvent arg0) {
        int row = table.getSelectedRow();
        if (row == -1) { // 如果用户没有选择任何行,则进行提示
            JOptionPane.showMessageDialog(this, "请选择要删除的用户", "",
                    JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (row >= 0) {
            int n = JOptionPane.showConfirmDialog(getContentPane(), "确认删除吗?",
                    "删除对话框", JOptionPane.YES_NO_CANCEL_OPTION);
            if (n == JOptionPane.YES_OPTION) { // 如果用户确认信息
                dao.deleteUser(Integer.parseInt(table.getValueAt(row, 0)
                        .toString()));
            }
            selecttable();
        }
    }

    // 关闭按钮的单击事件
    protected void do_button_1_actionPerformed(ActionEvent arg0) {
        int n = JOptionPane.showConfirmDialog(getContentPane(), "确认关闭吗?",
                "关闭对话框", JOptionPane.YES_NO_CANCEL_OPTION);
        if (n == JOptionPane.YES_OPTION) { // 如果用户确认信息
            System.exit(0);
        }
    }
}

3: 文件夹util
a:Users.java

package com.util;

/**
 * 
 * @author jiajikang 创建用户信息的实体类
 */
public class Users {

    // 成员变量
    // 用户id
    private int id;
    // 用户名
    private String username;
    // 用户密码
    private String password;
    // 用户权限
    private String popedom;

    // alt + shift + s + o ----成员方法
    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 String getPopedom() {
        return popedom;
    }

    public void setPopedom(String popodom) {
        this.popedom = popodom;
    }

}

b:UserUtil.java

package com.util;

/**
 * 
 * @author jiajikang
 * 功能:判断用户的权限
 */
public class UserUtil {
    // 成员变量
    private int popedom;
    static int n;

    // 构造方法
    public int getPopedom() {
        return popedom;
    }

    public void setPopedom(int popedom) {
        this.popedom = popedom;
        n=popedom;
    }
    public static int getNumber(){
        return n;
    }

}

注:
如何连接数据库加载驱动

4:结果

Java内容管理员 java管理员登录界面_java_02