4

在对我的用户进行身份验证后,我想在会话中引用当前登录的用户。

这里我如何在setCurrentUser方法中做到这一点:

FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
session.setAttribute("CURRENT_USER", currentUser);

不幸的是,session引用总是 null !

或者,我尝试使用 sessionMap

FacesContext facesContext = FacesContext.getCurrentInstance();
Map<String, Object> sessionMap = facesContext.getExternalContext().getSessionMap();
sessionMap.put("CURRENT_USER", currentUser);

它因这个例外而惨遭失败:

java.lang.UnsupportedOperationException
    at java.util.AbstractMap.put(AbstractMap.java:186)
    (...)

我究竟做错了什么 ?

我的控制器的完整代码

用户控制器.java

public class UserController implements Filter {
    private FilterConfig fc;
    private static final String CURRENT_USER = "CURRENT_USER";

    public void init(FilterConfig filterConfig) throws ServletException {
        fc = filterConfig;
        log(">> Filter initialized");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Authenticate user
        // ...

        // Save refernce in Session
        setCurrentUser(currentUser);

        //(...)
    }

    public static void setCurrentUser(User u) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
        session.setAttribute(CURRENT_USER, u);// session is always NULL
    }

    public static User getCurrentUser() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);       
        return (User)session.getAttribute(CURRENT_USER);
    }

    //...   
}

JSF 2.0
JBoss 5.1.0.GA

4

2 回答 2

11

FacesContexta 中不可用,Filter因为在之前Filter调用了。FacesServlet

您应该request改为从参数中获取会话。

HttpSession session = ((HttpServletRequest) request).getSession();
session.setAttribute("user", currentUser);
// ...

一旦您在 JSF 上下文中(例如,在 JSF 托管 bean 或 JSF 视图中),那么这将在getSessionMap()相同的属性名称上可用

User user = (User) externalContext.getSessionMap().get("user");

或者只是#{user}在 EL 中:

@ManagedProperty("#{user}")
private User user;
于 2012-06-13T11:57:29.890 回答
-1

这是我所做的:

public class SesionUtil implements Serializable {

    private static final long serialVersionUID = 1L;

    public void setSesionUsuario(String key, Object value) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(key, value);
    }

    public String getSesionUsuario(String key) {
        return FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(key).toString();
    }
}

然后,为了初始化会话,我简单地执行了:

@Inject // Inject dependency
private SesionUtil sessionUtil;

...

sessionUtil.setSesionUsuario("nombreUsuario",nombre);
于 2017-08-22T16:11:57.643 回答