使用MVC Java创建简单示例

时间:2012-12-14 06:34:40

标签: java model-view-controller

我有一个使用MVC模型检查用户登录的简单示例。

LoginModel:

public class LoginModel {
private String username;
private String password;

public LoginModel()
{        
}
/**
 * @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;
}

}

LoginView:

public class LoginView {
LoginModel user;

//Ham khoi tao cho LoginView
public LoginView(LoginModel user)
{
  this.user=user;
}

public void showMessage(String msg)
{
  System.out.println(msg);
}

public void getUserInfo()
{
try
{

    DataInputStream input=new DataInputStream(System.in);
    System.out.println("Username:");
    user.setUsername(input.readUTF());
    System.out.println("Password:");
    user.setPassword(input.readUTF());
    input.close();
}
catch(IOException e)
{
    System.out.println(e);
}

} }

LoginControl:

public class LoginControl {
LoginModel user;
LoginView view;

public LoginControl(LoginModel user,LoginView view)
{
    this.user=user;
    this.view=view;
    while(true)
    {
    view.getUserInfo();
    if(checkLogin())
    {
        view.showMessage("Success");
    }
    else
    {
        view.showMessage("Wrong username or password");
    }
    }
}

private boolean checkLogin()
{
    if((user.getUsername().equals("sa"))&&(user.getPassword().equals("sa")))
    {
        return true;
    }
    return false;
}

}

LoginMain:

public class LoginMVC {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    LoginModel user=new LoginModel();
    LoginView view=new LoginView(user);
    LoginControl control=new LoginControl(user, view);
}

}

但是当我运行主类时,它只是用户名:并输入用户并停止.. 我不知道哪里出错。 你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

我不确定为什么DataInputStream无效,我建议使用ScannergetUserInfo方法中获取控制台的输入。

  Scanner scanner = new Scanner(System.in);
  System.out.println("Username:");
  user.setUsername(scanner.nextLine());
  System.out.println("Password:");
  user.setPassword(scanner.nextLine());
  scanner.close();