4
\$\begingroup\$

I'm new to MVC. I have made small implementation in Java Swing using MVC pattern. I want little help from you to check if the code is appropriate to MVC pattern or not.

So here is my code:

1. LoginView.java

This is GUI class designed using Java Swing API. It consist of two textbox, username and password; one login button and one label to display an error message. It has an event handler for button click. When user clicks this button, the method from controller class is called along with credentials like username and password is passed to it.

package com.mvc.view;

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import com.mvc.controller.LoginController;

public class LoginView extends JFrame {

    private static final long serialVersionUID = 3566038652320101414L;
    private JTextField txtUsername;
    private JPasswordField txtPassword;
    private JButton btnLogin;
    private JLabel lblErrorMessage;

    public LoginView() {
        setTitle("MedIT: Login");
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 400, 250);
        Container contentPane = this.getContentPane();
        contentPane.setLayout(null);

        JLabel lblUsername = new JLabel("Username:");
        lblUsername.setFont(new Font("Tahoma", Font.BOLD, 14));
        lblUsername.setHorizontalAlignment(SwingConstants.RIGHT);
        lblUsername.setBounds(10, 11, 120, 25);
        contentPane.add(lblUsername);

        txtUsername = new JTextField();
        txtUsername.setFont(new Font("Tahoma", Font.PLAIN, 14));
        txtUsername.setBounds(140, 11, 200, 25);
        contentPane.add(txtUsername);

        JLabel lblPassword = new JLabel("Password:");
        lblPassword.setHorizontalAlignment(SwingConstants.RIGHT);
        lblPassword.setFont(new Font("Tahoma", Font.BOLD, 14));
        lblPassword.setBounds(10, 52, 120, 25);
        contentPane.add(lblPassword);

        txtPassword = new JPasswordField();
        txtPassword.setFont(new Font("Tahoma", Font.PLAIN, 14));
        txtPassword.setBounds(140, 52, 200, 25);
        contentPane.add(txtPassword);

        LoginController controller = new LoginController(this);
        btnLogin = new JButton("Login");
        btnLogin.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent arg0) {
                controller.checkCredentials(txtUsername.getText(), new String(txtPassword.getPassword()));
            }
        });
        btnLogin.setFont(new Font("Tahoma", Font.PLAIN, 14));
        btnLogin.setBounds(251, 93, 89, 25);
        contentPane.add(btnLogin);

        lblErrorMessage = new JLabel("");
        lblErrorMessage.setHorizontalAlignment(SwingConstants.RIGHT);
        lblErrorMessage.setForeground(Color.RED);
        lblErrorMessage.setFont(new Font("Tahoma", Font.PLAIN, 14));
        lblErrorMessage.setBounds(10, 151, 330, 25);
        contentPane.add(lblErrorMessage);
    }

    public void setErrorMessage(String errorMessage) {
        lblErrorMessage.setText(errorMessage);
    }

    public static void main(String args[]){
        LoginView view = new LoginView();
        view.setVisible(true);
    }
}

2. LoginController.java

This class consist of business logic, that is it checks whether the passed credentials like username and password are right credentials for authentication of user or not. So we have checkCredentials method in it. This method first ask for the data of user to the Model class. If the username and password makes appropriate match the "Login Success!" message is passed to View other wise "Login Failed!" message is passed.

package com.mvc.controller;

import com.mvc.model.LoginModel;
import com.mvc.view.LoginView;

public class LoginController {

    private LoginView view;
    private LoginModel model;

    public LoginController(LoginView view){
        this.view = view;
        model = new LoginModel();
    }

    public void checkCredentials(String username, String password){
        model.setUsername(username);
        model.getCredentials();
        if(password.equals(model.getPassword())){
            view.setErrorMessage("Login Success!");
        }
        else{
            view.setErrorMessage("Login Failed!");
        }
    }
}

3. LoginModel.java

This is the model class. Appropriate data is fetched from the database according to controller's call. It has setters and getters methods.

package com.mvc.model;

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

public class LoginModel {
    private String username, password;
    private Connection conn;

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void getCredentials(){
        try {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            conn = DriverManager.getConnection("jdbc:derby:db/medit");
            PreparedStatement select = conn.prepareStatement("SELECT * FROM user_credentials WHERE username = ?");
            select.setString(1, username);
            ResultSet rs = select.executeQuery();
            if(rs.next()){
                password = rs.getString("password");
            }
            else{
                password = "";
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (SQLException e) {
            e.printStackTrace();
        }
        finally{
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
\$\endgroup\$
2
\$\begingroup\$

You have the word Tahoma several times in your code. It should only appear once, in a helper method setStyle(JComponent), which in turn is used by the two helper methods createLabel and createTextBox.

You must not store the passwords directly in the database, to prevent data leaks. Use bcrypt password hashing instead.

e.printStackTrace is not proper error handling since the user doesn't get any feedback. The user must be informed if something goes wrong.

Methods called getSomething must not have side effects. Use load instead of get.

\$\endgroup\$
  • \$\begingroup\$ Thanks @RolandIllig. I would also like to know about MVC pattern. Is the code above is appropriate to MVC pattern? \$\endgroup\$ – Anirudha Mahadik Sep 6 '17 at 7:29
  • \$\begingroup\$ I don't know, therefore I only commented on the other things. Personally, I don't like that the model has its own database connection. I prefer model types to be just data, without any behavior. \$\endgroup\$ – Roland Illig Sep 6 '17 at 7:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.