今天看了《Struts in Action 中文版》一书。本来是打算照例子去做个简单的Struts程序
但是发现了UserDirectory这个类,作者没给出来。不过最终还是给弄出来了
下面就是UserDirectory的代码,给大家共享一下吧^_^
package com.mystruts.struts;
import java.io.IOException;
//import java.io.InputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.Properties;
public class UserDirectory {
private static final String UserDirectoryFile = "resources/users.properties";
private static final String UserDirectoryHeader = "${user}=${password}";
private static UserDirectory userDirectory = null;
private static Properties p;
private UserDirectory() throws Exception {
java.io.InputStream i = null;
p = null;
i = this.getClass().getClassLoader().
getResourceAsStream(UserDirectoryFile);
if (null==i) {
throw new Exception();
}
else {
try {
p = new Properties();
p.load(i);
i.close();
}
catch (java.io.IOException e) {
p = null;
System.out.println(e.getMessage());
throw new Exception();
}
finally {
i = null;
}
} // end else
} // end UserDirectory
public static UserDirectory getInstance() throws
Exception {
if (null==userDirectory) {
userDirectory = new UserDirectory();
}
return userDirectory;
}
public String fixId(String userId) {
return userId.toUpperCase();
}
public boolean isValidPassword(String userId, String
password) {
// no null passwords
if (null==password) return false;
// conform userId to uppercase
String _userId = fixId(userId);
// no passwords for non-users
if (!isUserExist(_userId)) return false;
// does password match user's password
return (password.equals(getPassword(_userId)));
}
public boolean isUserExist(String userId) {
// no null users
if (null==userId) return false;
// if not null, it's a user
return !(null==p.getProperty(userId));
}
public String getPassword(String userId) {
return p.getProperty(userId);
}
public Enumeration getUserIds() {
return p.propertyNames();
}
public void setUser(String userId, String password)
throws
Exception {
// no nulls
if ((null==userId) || (null==password)) {
throw new Exception();
}
try {
// conform userId to uppercase when stored
p.put(fixId(userId), password);
p.store(new FileOutputStream(UserDirectoryFile),
UserDirectoryHeader);
}
catch (IOException e) {
throw new Exception();
}
}
} // end UserDirectory
阅读(3773) | 评论(2) | 转发(0) |