問題描述
在桌面應用程序中保存用戶名和密碼 (Saving username & password in desktop app)
I am making one frame which has two text field one for username & other for password,and one button to login.
Now I want to store my login information for a specified period of time , so that next time when user open my frame he'll be able to retrieve his login information. I know this is possible through cookies, but I need to know how to apply this concept in my frame.
My application is a windows based application, no link to browser.
How to achieve this feature?
參考解法
方法 1:
You can client information to the system in any number of ways...
You could
Use Properties
, which allow you to specify key/name pairs of information, which can loaded and saved to a file.
You could
Use the Preferences API which is simluar to the Properties
API, except you get the added benifit of internal persistence (you don't need to read/write the files), groupings (you can have a key
specified multiple times, so long as it's in different groups)
As a side note. You shouldn't be storing passwords in any manner that they might be retrieved. Instead you should store using something like a MD5 hash and compare hashs. See Convert MD5 into String in java for more details...
方法 2:
You might like to use temporary file to write the user detail. File tempFile = File.createTempFile("temp‑file‑name", ".tmp"); The next time the user comes, you can read the data from that temp file. Additionally you can make the temp file hidden for more data security.
It seems the temp file name is appended by a random number so it will be better to create the temp file your self.
This code snippet might help you.
try {
String tempDir = System.getProperty("java.io.tmpdir");
File tempFile = new File(new File(tempDir), "userDetail.tmp");
if(tempFile.exists()){//This is subsequent login
//Write your code to read file and
//your application logic
}else{ //This is first login
tempFile.createNewFile();
//Write your logic to write data to the file
}
} catch (Exception ex) {
ex.printStackTrace();
}
You can refactor the code to suit your design.
(by user2303984、MadProgrammer、pundit)