2012-12-19 91 views
-2

我有一個用戶配置文件類,只是想知道加載它的最佳方式是。我有下面的代碼,並想知道它是否是正確的方式來做到這一點。從數據庫檢索配置文件 - Java

UserProfile userProfile = null; 
char[] password = {'a','b','c'}; 

for(UserProfile profile : UserProfiles){ 
    if(compareUserNameAndPassword("userName", password)){ 
     userProfile = profile; 
    } 

} 

而且我的個人資料類:

package jlibfprint; 

public class UserProfile extends Profile { 

    /** 
    * constructor 
    */ 
    public UserProfile(String userName, int id, char[] password){ 
     this.name = userName; 
     this.id = id; 
     this.password = password; 
    } 


    /** 
    * Users password 
    */ 
    private char[] password; 

    /** 
    * Set User password 
    * @param password 
    */ 
    public void setPassword(char[] password){ 

     this.password = password; 

    } 

    /** 
    * compare passwords 
    */ 
    public boolean compareUserNameAndPassword(String userName,char[] password) { 

     if(this.name.equals(userName) && this.password.equals(password)){ 

      return true; 

     } 
     return false; 

    } 
} 
+1

你的負載是什麼意思? – unholysampler

+0

你的意思是最好的? –

+0

你的代碼甚至不會編譯。 – 2012-12-19 20:48:35

回答

1

這不是classloading,它的檢查是一個類的實例對象。它應該是profile.compareUserNameAndPassword(userName,password)

你現在這樣做的方式意味着你所有的UserProfile都在記憶中。通常他們會在數據庫中,你會在查詢中進行用戶名和密碼比較,然後只有匹配的時候才能獲取。

您可能還想考慮是否應該在某個時候對密碼進行散列處理。

您可能還應該考慮不要「重新發明輪子」並借用一些框架工具來提供幫助。 Hibernate是一個對象關係管理工具,旨在簡化從數據庫中檢索Java對象。 Spring是一個框架,它有助於促進良好的設計技術和管理授權和認證,以及MVC方法

/* 
    * Retrieves a UserProfile from the database based on a username and password 
    * Needs Apache Commons Codec package otherwise you have to use MessageDigest 
    * which gives a binary SHA-1 
    * @param username The username to fetch 
    * @param password The unhashed password 
    * @return The UserProfile or null if the user was not found in the DB 
    */ 
private static UserProfile retrieveUserProfile(String username, char[] password) 
    throws SQLException { 
    password = DigestUtils.sha1Hex(password); 
    //Assuming a pre-setup JDBC Connection object - `con` 
    final String updateString = "SELECT userName, password FROM userProfiles" 
     + "WHERE username = ? AND password = ? LIMIT 1"; 
    PreparedStatement retrieveUserProfile = con.prepareStatement(updateString) 
    retrieveUserProfile.setString(1,"username"); 
    retrieveUserProfile.setString(2,"password"); 
    ResultSet rs = retrieveUserProfile.execute(); 
    if(rs.next()) { 
     return new UserProfile(username,password); 
    } 
    else { 
     //User Not found 
     return null; 
    } 
} 
+0

因此,類加載是我應該看到?我打算擁有一個我可以在運行時加載的配置文件對象的數據庫 – TomSelleck

+1

不,這完全是錯誤的使用術語。我會用一個數據庫加載的例子來更新我的回覆(儘管像Hibernate這樣可以讓這個更容易)。 –

+1

在UserProfile **對象**的檢索和返回可能已完成的情況下,添加了一個完全「我的頭頂」的嘗試。 –