好吧,我有一些必须对所有应用程序(DAO,Business Object,Beans和其他人)都可访问的会话属性。
我无法创建具有静态属性的类,因为静态属性会分享给不同的会话。
IE:用户登录应用程序,我需要保存登录时间,我需要将此值存储在会话属性中,因为在我的应用程序的某些方面,如BO(业务对象),我将需要知道用户登录应用程序时。我无法在我的应用程序的某些地方访问HttpRequest,我需要另一种解决方案。
答案 0 :(得分:0)
public PojoFilter implements javax.servlet.Filter {
private static final ThreadLocal<Pojo> POJO = new ThreadLocal<Pojo>();
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {
try {
Pojo pojo = createPojoFrom(request);
POJO.set(pojo);
filterChain.doFilter(request, response);
} finally {
POJO.remove();
}
}
public static currentPojo() {
return POJO.get();
}
...
}
显然,这可以设计得更好,以便过滤器不会泄漏到代码的其余部分,但这应该会给你一个想法。
答案 1 :(得分:0)
您已在JSF中对此进行了标记,因此我将为您提供jsf响应和/或通用。
a)创建一个@SessionScoped
- ManagedBean并将值应用于它,然后@ManagedProperty
将其注入您想要访问它的需求位置(如果需要,可以创建一个外观)。
b)只需创建一个数据模型&#39;对象将您的信息存储在其中并将其设置为会话。 E.g
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("userContext", context);
答案 2 :(得分:0)
Since user id is unique, we can utilize this fact to implement your problem in simpler way as follows(My solution consider that all incoming request goes through common servlet/filter, I am using filter here):
a) Create a utility class as:
public class AppUtlity {
private static Map<String, Date> userLoginTimeStampMap = new HashMap<String, Date>();
public static void addLoginTimeStamp(String userId) {
synchronized(AppUtlity.class) {
Date date = new Date();
userLoginTimeStampMap.put(userId, date);
}
}
public static Date getUserLoginTimeStamp(String userId) {
synchronized(AppUtlity.class) {
return userLoginTimeStampMap.get(userId);
}
}
}
b) In doFilter method of your filter write code as below:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {
try {
String userId = user.getUserId();
AppUtlity.addLoginTimeStamp(userId);
} finally {
// do whatever u want to do
}
}
c) Now in any class like service or dao, you can easily get user login timestamp as below:
Date date = AppUtlity.getUserLoginTimeStamp(userId);
I hope this solution is feasible.