说真的,第一次看到MVC时候的感觉就和看到面向对象编程一样,感觉很方。之后慢慢的写了一些代码,在理解面向对象编程的同时也看到了MVC,虽然现在还是用不到,但是我觉得还是有些了解的好。
先谈谈MVC:模型(model):程序员编写程序应有的功能(实现算法等等)、数据库专家进行数据管理和数据库设计(可以实现具体的功能)。
视图(view):设计界面。
控制(Controller):处理事务。
很多地方可能我理解的不是很到位。只是能写出来一个大概,后续我还会更新。又重新查了一遍资料,感觉又开始有一种模糊的感觉,不理解什么是MVC了。先写,之后再修改。
一共写了四个包,dao(用来处理数据库操作的各项),model(创建了一个模型user),util(工具包,连接数据库和关闭连接),view(界面设计)。
我们先新建一个数据库:db_login,然后在数据库下添加一个表,叫做user。
就是这么一个样子。
然后我们去设计一下model下的user类:和数据库中的一一对应,id(int),userName(String),password(String)。
1 package com.rookie.model; 2 3 public class User { 4 private int id; 5 private String userName; 6 private String password; 7 8 public User() { 9 super(); 10 // TODO Auto-generated constructor stub 11 } 12 13 public User(String userName, String password) { 14 super(); 15 this.userName = userName; 16 this.password = password; 17 } 18 19 public int getId() { 20 return id; 21 } 22 23 public void setId(int id) { 24 this.id = id; 25 } 26 27 public String getUserName() { 28 return userName; 29 } 30 31 public void setUserName(String userName) { 32 this.userName = userName; 33 } 34 35 public String getPassword() { 36 return password; 37 } 38 39 public void setPassword(String password) { 40 this.password = password; 41 } 42 43 }
model类写好之后我们就去写util包下的DbUtil类。我用的是MySQL数据库,所以先去官网下载了Jar包,build-path导入包。然后开始写util中的控制包。
和正常的数据库连接一样。
1 package com.rookie.util; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 8 public class DbUtil { 9 10 String dbUrl = "jdbc:mysql://localhost:3306/db_login"; 11 String dbUser = "root"; 12 String dbPass = "salin"; 13 String driveName = "com.mysql.jdbc.Driver"; 14 15 public Connection getCon()throws Exception { 16 Class.forName(driveName); 17 Connection con = DriverManager.getConnection(dbUrl,dbUser,dbPass); 18 return con; 19 } 20 21 public void closeCon(Connection con) { 22 if(con!=null) { 23 try { 24 con.close(); 25 } catch (SQLException e) { 26 e.printStackTrace(); 27 } 28 } 29 } 30 }
这里只写了创建连接和关闭连接,我把剩下的数据库增删改放在了Dao包下(很多地方说Dao包相当于MVC中的model)。
接下来的话我打算去设计View类,View分成了两部分,一部分是登陆界面,一部分是注册界面(小小的加深一下)。
整体界面就是这样,那些图标是在:http://www.easyicon.net 找的。值得一说的是注册账户哪里是一个标签,然后加入了鼠标点击监听(mouseClickedAction),点击之后就会弹出一个注册界面:
没有很高大上的样子,就是为了能够多理解一下MVC。这个界面的设计还是使用了 WindowsBuilder 插件。很方便,而且也加入了自己的一些想法,比如鼠标进入编辑框后会把编辑框的边框变色,还有一些东西是在开发的时候才能找到。下面直接贴代码:
1 package com.rookie.view; 2 3 import java.awt.EventQueue; 4 5 import javax.swing.JFrame; 6 import javax.swing.JPanel; 7 import javax.swing.border.EmptyBorder; 8 import javax.swing.border.LineBorder; 9 10 import com.rookie.dao.UserDao; 11 import com.rookie.model.User; 12 import com.rookie.util.DbUtil; 13 14 import javax.swing.JLabel; 15 import javax.swing.JOptionPane; 16 import javax.swing.JTextField; 17 import javax.swing.JPasswordField; 18 import javax.swing.JButton; 19 import java.awt.event.ActionListener; 20 import java.sql.Connection; 21 import java.awt.event.ActionEvent; 22 import javax.swing.SwingConstants; 23 import java.awt.Font; 24 import java.awt.Toolkit; 25 import java.awt.Color; 26 27 28 import java.awt.event.MouseAdapter; 29 import java.awt.event.MouseEvent; 30 import javax.swing.ImageIcon; 31 32 public class UserLogin extends JFrame { 33 /** 34 * 用户登陆界面。 35 */ 36 private static final long serialVersionUID = 1L; 37 private JPanel contentPane; 38 private JPasswordField text_password; 39 private JButton bt_login; 40 private JLabel l_Prompt; 41 private Connection con; 42 private DbUtil dbUtil; 43 private UserDao userDao; 44 private JLabel label_2; 45 private JTextField text_username; 46 private final int WINDOWWIDTH = 386; 47 private final int WINDOWHEIGH = 256; 48 /** 49 * Launch the application. 50 */ 51 public static void main(String[] args) { 52 EventQueue.invokeLater(new Runnable() { 53 public void run() { 54 try { 55 UserLogin frame = new UserLogin(); 56 frame.setVisible(true); 57 } catch (Exception e) { 58 e.printStackTrace(); 59 } 60 } 61 }); 62 } 63 64 /** 65 * Create the frame. 66 */ 67 public UserLogin() { 68 setTitle("\u6B22\u8FCE\u767B\u9646"); 69 setResizable(false); 70 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 71 contentPane = new JPanel(); 72 contentPane.setLayout(null); 73 contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 74 setContentPane(contentPane); 75 76 JLabel label = new JLabel("\u7528\u6237\u540D\uFF1A"); 77 label.setIcon(new ImageIcon(UserLogin.class.getResource("/icon/user.png"))); 78 label.setFont(new Font("黑体", Font.PLAIN, 12)); 79 label.setBounds(60, 66, 68, 27); 80 contentPane.add(label); 81 82 JLabel label_1 = new JLabel("\u5BC6 \u7801\uFF1A"); 83 label_1.setIcon(new ImageIcon(UserLogin.class.getResource("/icon/pass.png"))); 84 label_1.setFont(new Font("黑体", Font.PLAIN, 12)); 85 label_1.setBounds(60, 103, 68, 27); 86 contentPane.add(label_1); 87 88 text_password = new JPasswordField(); 89 text_password.addMouseListener(new MouseAdapter() { 90 @Override 91 public void mouseExited(MouseEvent e) { 92 mouseExitedAction(e); 93 } 94 @Override 95 public void mouseEntered(MouseEvent e) { 96 mouseEnteredAction(e); 97 } 98 }); 99 text_password.setBounds(138, 106, 124, 21); 100 contentPane.add(text_password); 101 102 bt_login = new JButton("\u767B\u9646"); 103 bt_login.setIcon(new ImageIcon(UserLogin.class.getResource("/icon/Login.png"))); 104 bt_login.addActionListener(new ActionListener() { 105 public void actionPerformed(ActionEvent e) { 106 loginAction(e); 107 } 108 }); 109 bt_login.setBounds(138, 160, 91, 40); 110 contentPane.add(bt_login); 111 112 l_Prompt = new JLabel(""); 113 l_Prompt.setForeground(Color.RED); 114 l_Prompt.setFont(new Font("黑体", Font.PLAIN, 13)); 115 l_Prompt.setHorizontalAlignment(SwingConstants.CENTER); 116 l_Prompt.setBounds(10, 29, 360, 27); 117 contentPane.add(l_Prompt); 118 119 label_2 = new JLabel("\u6CE8\u518C\u8D26\u6237"); 120 label_2.addMouseListener(new MouseAdapter() { 121 @Override 122 public void mouseClicked(MouseEvent e) { 123 new RegistUser().setVisible(true);; 124 } 125 @Override 126 public void mouseEntered(MouseEvent e) { 127 new RegistUser(); 128 } 129 }); 130 label_2.setForeground(Color.BLUE); 131 label_2.setBounds(284, 66, 53, 27); 132 contentPane.add(label_2); 133 134 text_username = new JTextField(); 135 text_username.addMouseListener(new MouseAdapter() { 136 @Override 137 public void mouseEntered(MouseEvent e) { 138 mouseEnteredAction(e); 139 } 140 @Override 141 public void mouseExited(MouseEvent e) { 142 mouseExitedAction(e); 143 } 144 }); 145 text_username.setBounds(138, 69, 124, 21); 146 contentPane.add(text_username); 147 text_username.setBorder(new LineBorder(new Color(0,0,0),1,false)); 148 text_password.setBorder(new LineBorder(new Color(0,0,0),1,false)); 149 text_username.setColumns(10); 150 151 int width = Toolkit.getDefaultToolkit().getScreenSize().width; 152 int heigh = Toolkit.getDefaultToolkit().getScreenSize().height; 153 int x = (width-WINDOWWIDTH)/2; 154 int y = (heigh-WINDOWHEIGH)/2; 155 this.setBounds(x, y, WINDOWWIDTH, WINDOWHEIGH); 156 } 157 //鼠标进入编辑框事件 158 private void mouseExitedAction(MouseEvent e) { 159 // TODO Auto-generated method stub 160 JTextField text = (JTextField)e.getSource(); 161 text.setBorder(new LineBorder(new Color(0,0,0),1,false)); 162 } 163 //鼠标退出编辑框事件 164 private void mouseEnteredAction(MouseEvent e) { 165 // TODO Auto-generated method stub 166 JTextField text = (JTextField)e.getSource(); 167 text.setBorder(new LineBorder(new Color(0,0,255),1,false)); 168 } 169 170 private void loginAction(ActionEvent e) { 171 User user = new User(); 172 String userName = text_username.getText(); 173 char[] pass = text_password.getPassword(); 174 String password = String.valueOf(pass); 175 if(userName == null || userName.equals("")) { 176 l_Prompt.setText("用户名不能为空!"); 177 return ; 178 }else if(password == null || password.equals("")){ 179 l_Prompt.setText("密码不能为空!"); 180 return ; 181 } 182 user.setUserName(userName); 183 user.setPassword(password); 184 try { 185 dbUtil = new DbUtil(); 186 userDao = new UserDao(); 187 con = dbUtil.getCon(); 188 User loginUser = userDao.login(con, user); 189 if( loginUser != null ) { 190 l_Prompt.setText("登陆成功,欢迎使用!"); 191 }else { 192 l_Prompt.setText("用户名或密码错误!"); 193 } 194 } catch (Exception e1) { 195 dbUtil.closeCon(con); 196 } finally { 197 dbUtil.closeCon(con); 198 } 199 } 200 }
UserLogin
1 package com.rookie.view; 2 3 4 import javax.swing.JButton; 5 import javax.swing.JDialog; 6 import javax.swing.JPasswordField; 7 8 import com.rookie.dao.RegisDao; 9 import com.rookie.dao.UserDao; 10 import com.rookie.model.User; 11 import com.rookie.util.DbUtil; 12 13 import javax.swing.JLabel; 14 import javax.swing.JTextField; 15 import java.awt.event.ActionListener; 16 import java.sql.Connection; 17 import java.awt.Toolkit; 18 import java.awt.event.ActionEvent; 19 import javax.swing.SwingConstants; 20 import java.awt.Color; 21 import javax.swing.ImageIcon; 22 23 public class RegistUser extends JDialog { 24 private Connection con; 25 private DbUtil dbUtil; 26 private RegisDao regisDao; 27 private JTextField text_userName; 28 private JPasswordField text_password; 29 private JPasswordField text_repeat; 30 private JLabel prompt; 31 private final int WINDOWWIDTH = 296; 32 private final int WINDOWHEIGH = 300; 33 34 /** 35 * Launch the application. 36 */ 37 public static void main(String[] args) { 38 try { 39 RegistUser dialog = new RegistUser(); 40 dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 41 dialog.setVisible(true); 42 } catch (Exception e) { 43 e.printStackTrace(); 44 } 45 } 46 47 /** 48 * Create the dialog. 49 */ 50 public RegistUser() { 51 getContentPane().setForeground(Color.RED); 52 setTitle("\u7528\u6237\u6CE8\u518C"); 53 setAlwaysOnTop(true); 54 getContentPane().setLayout(null); 55 56 JLabel label = new JLabel("*\u7528\u6237\u540D\uFF1A"); 57 label.setIcon(new ImageIcon(RegistUser.class.getResource("/icon/user.png"))); 58 label.setBounds(36, 42, 77, 18); 59 getContentPane().add(label); 60 61 JLabel label_1 = new JLabel("*\u5BC6 \u7801\uFF1A"); 62 label_1.setIcon(new ImageIcon(RegistUser.class.getResource("/icon/pass.png"))); 63 label_1.setBounds(36, 80, 77, 15); 64 getContentPane().add(label_1); 65 66 text_userName = new JTextField(); 67 text_userName.setBounds(123, 42, 113, 21); 68 getContentPane().add(text_userName); 69 text_userName.setColumns(10); 70 71 text_password = new JPasswordField(); 72 text_password.setEchoChar(‘*‘); 73 text_password.setColumns(10); 74 text_password.setBounds(123, 77, 113, 21); 75 getContentPane().add(text_password); 76 77 JLabel label_2 = new JLabel("*\u91CD\u590D\u5BC6\u7801\uFF1A"); 78 label_2.setBounds(47, 122, 77, 15); 79 getContentPane().add(label_2); 80 81 text_repeat = new JPasswordField(); 82 text_repeat.setEchoChar(‘*‘); 83 text_repeat.setColumns(10); 84 text_repeat.setBounds(123, 119, 113, 21); 85 getContentPane().add(text_repeat); 86 87 JButton button = new JButton(""); 88 button.setIcon(new ImageIcon(RegistUser.class.getResource("/icon/Register.png"))); 89 button.addActionListener(new ActionListener() { 90 public void actionPerformed(ActionEvent e) { 91 addUserAction(e); 92 } 93 }); 94 button.setBounds(36, 185, 77, 33); 95 getContentPane().add(button); 96 97 JButton button_1 = new JButton(""); 98 button_1.setIcon(new ImageIcon(RegistUser.class.getResource("/icon/reset.png"))); 99 button_1.addActionListener(new ActionListener() { 100 public void actionPerformed(ActionEvent e) { 101 text_password.setText(""); 102 text_repeat.setText(""); 103 text_userName.setText(""); 104 prompt.setText(""); 105 } 106 }); 107 button_1.setBounds(165, 185, 71, 33); 108 getContentPane().add(button_1); 109 110 prompt = new JLabel(""); 111 prompt.setForeground(Color.RED); 112 prompt.setHorizontalAlignment(SwingConstants.CENTER); 113 prompt.setBounds(36, 160, 200, 15); 114 getContentPane().add(prompt); 115 116 int width = Toolkit.getDefaultToolkit().getScreenSize().width; 117 int heigh = Toolkit.getDefaultToolkit().getScreenSize().height; 118 int x = (width-WINDOWWIDTH)/2; 119 int y = (heigh-WINDOWHEIGH)/2; 120 this.setBounds(x, y, 286, 278); 121 } 122 123 protected void addUserAction(ActionEvent e) { 124 // TODO Auto-generated method stub 125 String userName = text_userName.getText(); 126 char []pass = text_password.getPassword(); 127 String password = String.valueOf(pass); 128 char []rep = text_repeat.getPassword(); 129 String repeat = String.valueOf(rep); 130 if(userName.length() < 6) { 131 prompt.setText("用户名长度错误!"); 132 return ; 133 }else if( !password.equals(repeat) || (password.length() < 6 || password.length() > 20)){ 134 prompt.setText("密码存在问题!"); 135 return ; 136 } 137 User user = new User(userName, password); 138 dbUtil = new DbUtil(); 139 regisDao = new RegisDao(); 140 try { 141 con = dbUtil.getCon(); 142 boolean hasUser= regisDao.hasUser(con, user); 143 if( hasUser == false) { 144 regisDao.addUser(con, user); 145 prompt.setText("添加成功!"); 146 }else { 147 prompt.setText("用户名已存在!"); 148 } 149 } catch (Exception e1) { 150 // TODO Auto-generated catch block 151 e1.printStackTrace(); 152 } finally { 153 dbUtil.closeCon(con); 154 } 155 } 156 157 }
RegistUser
写完界面之后就是Dao类了,用来处理数据库事件,我也写了两个对应上面的View界面,一个是登陆,一个是注册。用了MySQL语句,并不是很难。
1 package com.rookie.view; 2 3 4 import javax.swing.JButton; 5 import javax.swing.JDialog; 6 import javax.swing.JPasswordField; 7 8 import com.rookie.dao.RegisDao; 9 import com.rookie.dao.LoginDao; 10 import com.rookie.model.User; 11 import com.rookie.util.DbUtil; 12 13 import javax.swing.JLabel; 14 import javax.swing.JTextField; 15 import java.awt.event.ActionListener; 16 import java.sql.Connection; 17 import java.awt.Toolkit; 18 import java.awt.event.ActionEvent; 19 import javax.swing.SwingConstants; 20 import java.awt.Color; 21 import javax.swing.ImageIcon; 22 23 public class RegistUser extends JDialog { 24 private Connection con; 25 private DbUtil dbUtil; 26 private RegisDao regisDao; 27 private JTextField text_userName; 28 private JPasswordField text_password; 29 private JPasswordField text_repeat; 30 private JLabel prompt; 31 private final int WINDOWWIDTH = 296; 32 private final int WINDOWHEIGH = 300; 33 34 /** 35 * Launch the application. 36 */ 37 public static void main(String[] args) { 38 try { 39 RegistUser dialog = new RegistUser(); 40 dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 41 dialog.setVisible(true); 42 } catch (Exception e) { 43 e.printStackTrace(); 44 } 45 } 46 47 /** 48 * Create the dialog. 49 */ 50 public RegistUser() { 51 getContentPane().setForeground(Color.RED); 52 setTitle("\u7528\u6237\u6CE8\u518C"); 53 setAlwaysOnTop(true); 54 getContentPane().setLayout(null); 55 56 JLabel label = new JLabel("*\u7528\u6237\u540D\uFF1A"); 57 label.setIcon(new ImageIcon(RegistUser.class.getResource("/icon/user.png"))); 58 label.setBounds(36, 42, 77, 18); 59 getContentPane().add(label); 60 61 JLabel label_1 = new JLabel("*\u5BC6 \u7801\uFF1A"); 62 label_1.setIcon(new ImageIcon(RegistUser.class.getResource("/icon/pass.png"))); 63 label_1.setBounds(36, 80, 77, 15); 64 getContentPane().add(label_1); 65 66 text_userName = new JTextField(); 67 text_userName.setBounds(123, 42, 113, 21); 68 getContentPane().add(text_userName); 69 text_userName.setColumns(10); 70 71 text_password = new JPasswordField(); 72 text_password.setEchoChar(‘*‘); 73 text_password.setColumns(10); 74 text_password.setBounds(123, 77, 113, 21); 75 getContentPane().add(text_password); 76 77 JLabel label_2 = new JLabel("*\u91CD\u590D\u5BC6\u7801\uFF1A"); 78 label_2.setBounds(47, 122, 77, 15); 79 getContentPane().add(label_2); 80 81 text_repeat = new JPasswordField(); 82 text_repeat.setEchoChar(‘*‘); 83 text_repeat.setColumns(10); 84 text_repeat.setBounds(123, 119, 113, 21); 85 getContentPane().add(text_repeat); 86 87 JButton button = new JButton(""); 88 button.setIcon(new ImageIcon(RegistUser.class.getResource("/icon/Register.png"))); 89 button.addActionListener(new ActionListener() { 90 public void actionPerformed(ActionEvent e) { 91 addUserAction(e); 92 } 93 }); 94 button.setBounds(36, 185, 77, 33); 95 getContentPane().add(button); 96 97 JButton button_1 = new JButton(""); 98 button_1.setIcon(new ImageIcon(RegistUser.class.getResource("/icon/reset.png"))); 99 button_1.addActionListener(new ActionListener() { 100 public void actionPerformed(ActionEvent e) { 101 text_password.setText(""); 102 text_repeat.setText(""); 103 text_userName.setText(""); 104 prompt.setText(""); 105 } 106 }); 107 button_1.setBounds(165, 185, 71, 33); 108 getContentPane().add(button_1); 109 110 prompt = new JLabel(""); 111 prompt.setForeground(Color.RED); 112 prompt.setHorizontalAlignment(SwingConstants.CENTER); 113 prompt.setBounds(36, 160, 200, 15); 114 getContentPane().add(prompt); 115 116 int width = Toolkit.getDefaultToolkit().getScreenSize().width; 117 int heigh = Toolkit.getDefaultToolkit().getScreenSize().height; 118 int x = (width-WINDOWWIDTH)/2; 119 int y = (heigh-WINDOWHEIGH)/2; 120 this.setBounds(x, y, 286, 278); 121 } 122 123 protected void addUserAction(ActionEvent e) { 124 // TODO Auto-generated method stub 125 String userName = text_userName.getText(); 126 char []pass = text_password.getPassword(); 127 String password = String.valueOf(pass); 128 char []rep = text_repeat.getPassword(); 129 String repeat = String.valueOf(rep); 130 if(userName.length() < 6) { 131 prompt.setText("用户名长度错误!"); 132 return ; 133 }else if( !password.equals(repeat) || (password.length() < 6 || password.length() > 20)){ 134 prompt.setText("密码存在问题!"); 135 return ; 136 } 137 User user = new User(userName, password); 138 dbUtil = new DbUtil(); 139 regisDao = new RegisDao(); 140 try { 141 con = dbUtil.getCon(); 142 boolean hasUser= regisDao.hasUser(con, user); 143 if( hasUser == false) { 144 regisDao.addUser(con, user); 145 prompt.setText("添加成功!"); 146 }else { 147 prompt.setText("用户名已存在!"); 148 } 149 } catch (Exception e1) { 150 // TODO Auto-generated catch block 151 e1.printStackTrace(); 152 } finally { 153 dbUtil.closeCon(con); 154 } 155 } 156 157 }
LoginDao
1 package com.rookie.dao; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 8 import com.rookie.model.User; 9 10 public class RegisDao { 11 12 public RegisDao() { 13 super(); 14 // TODO Auto-generated constructor stub 15 } 16 17 public boolean hasUser(Connection con,User user) throws SQLException { 18 String sql = "select * from user where userName=?"; 19 PreparedStatement pra = con.prepareStatement(sql); 20 pra.setString(1, user.getUserName()); 21 ResultSet result = pra.executeQuery(); 22 if(result.next()) { 23 String userName = result.getString("userName"); 24 if(userName.equals(user.getUserName())) { 25 return true; 26 }else { 27 return false; 28 } 29 }else { 30 return false; 31 } 32 } 33 34 //添加用户 35 public int addUser(Connection con,User user) throws SQLException { 36 String sql = "insert into user(userName,password) values(?,?)"; 37 PreparedStatement pra = con.prepareStatement(sql); 38 pra.setString(1, user.getUserName()); 39 pra.setString(2, user.getPassword()); 40 int resultNum = pra.executeUpdate(); 41 pra.close(); 42 return resultNum; 43 } 44 45 46 47 }
RegisDao
学艺不精,还望多多指教。目前看来,MVC是将整个软件开发过程分成了三个部分而不是三个包,Model很多地方写着是数据库的处理,我是用Dao来代替,而把model写成了模型。
(图片来自网络)一种映射机制,并没有强制去规定哪个地方去写什么,就我目前而言,我更喜欢去在model封装数据库所对应的类。而控制层和view层是紧密联系的,甚至很多代码是无法独立出来的。
新手上路,请多包涵。
代码已经打包上传:链接:http://pan.baidu.com/s/1geDNPWR 密码:b6e0