【发布时间】:2011-12-10 13:07:59
【问题描述】:
此问题与writing a session timeout handler 上的上一个问题有关。
该线程中的答案涉及从 servlet 访问各种会话范围的托管 bean。建议(如 here 所示)是在过滤器中执行此操作:
HttpSession session = request.getSession(false);
User user = (session != null) ? (User) session.getAttribute("user") : null;
大概这会获取 User 类的会话 bean。问题是这不起作用。
问题在于 bean 存在于会话属性中,但它们是由 Weld 工具包装的。我写了 doFilter() 方法如下:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String sp = req.getServletPath();
System.out.println("------------------------");
System.out.println("doFilter(): " + sp);
if (!sp.startsWith("/javax")) { // eliminates many requests
HttpSession session = req.getSession();
Enumeration<String> en = session.getAttributeNames();
int count = 0;
while (en.hasMoreElements()) {
String e = en.nextElement();
System.out.println("Attribute " + ++count + ": " + e);
}
}
chain.doFilter(request, response);
}
当这转储会话属性时,我通常会得到这样的结果:
INFO: ------------------------
INFO: doFilter(): /Display.xhtml
INFO: Attribute 1: org.jboss.weld.context.http.HttpSessionContext#org.jboss.weld.bean-WEB-INF/lib/myfaces-extcdi-bundle-jsf20-1.0.1-ManagedBean-class org.apache.myfaces.extensions.cdi.jsf.impl.scope.conversation.EditableWindowContextManagerProxy
INFO: Attribute 2: org.jboss.weld.context.http.HttpSessionContext#org.jboss.weld.bean-MyApp5-ManagedBean-class com.app.Login
INFO: Attribute 3: org.jboss.weld.context.conversation.ConversationIdGenerator
INFO: Attribute 4: com.sun.faces.renderkit.ServerSideStateHelper.LogicalViewMap
INFO: Attribute 5: org.jboss.weld.context.ConversationContext.conversations
INFO: Attribute 6: facelets.ui.DebugOutput
INFO: Attribute 7: javax.faces.request.charset
INFO: Attribute 8: org.apache.myfaces.extensions.cdi.core.api.scope.conversation.WindowContext:EXISTING_WINDOW_ID_LIST
属性 #2 似乎代表了我想要的 bean。不用说,调用 session.getAttribute("login") 不起作用。
谁能说出如何访问底层托管 bean?我更愿意以一种与 Weld 无关的方式来做这件事,但这可能是不可能的。
【问题讨论】:
标签: jsf-2 servlet-filters cdi