gpt4 book ai didi

jsf - 用于授权的RequestFilter和SessionBean

转载 作者:行者123 更新时间:2023-12-01 15:21:17 24 4
gpt4 key购买 nike

我在 websphere 应用程序服务器 8 上使用 jsf 2.0。

我有一个授权用户的请求过滤器。用户根据 WebSEAL 验证自己的身份。用户角色保存在 MySQL 数据库中。我的 Requestfilter 从每个请求的 httpServletRequest 获取用户主体。然后我查看用户拥有哪个角色(在数据库中)。

这非常糟糕,因为我对每个请求都有一个数据库查询。

为了改进这一点,我想实现一个包含用户名和角色的 SessionBean。我的问题是,我无法从 requestfilter 获取 sessionbean。我尝试使用 sessionbean 作为过滤器类中的管理属性。

但是我总是遇到 NullpointerException,因为之前从未调用过 sessionbean。

那么我该怎么做呢?这是错误的方法吗?

最佳答案

JSF 商店 @SessionScoped @ManagedBean s 作为 HttpSession 的属性。所以,在 Filter 里面它们的可用方式如下:

HttpSession session = ((HttpServletRequest) request).getSession();
SessionBean sessionBean = (SessionBean) session.getAttribute("sessionBean");

但是,您需要考虑到,当作用域中尚不存在 bean 时,此方法不会自动创建 bean。当在新的 HTTP session 上首次调用过滤器时,就会出现这种情况。 Filtler即在FacesServlet之前调用。然后,您需要自己创建 session bean。

HttpSession session = ((HttpServletRequest) request).getSession();
SessionBean sessionBean = (SessionBean) session.getAttribute("sessionBean");

if (sessionBean == null) {
sessionBean = new SessionBean();
session.setAttribute("sessionBean", sessionBean);
}

// ...

sessionBean.setRole(role);

// ...

只要 session 范围内已经存在该实例,JSF 就不会用新实例覆盖它,而只是重用 Filter 中创建的相同实例。 .

如果您已经在使用 CDI @Named管理 bean 而不是 JSF 2.3 中的 已弃用且 Faces 4.0 已删除 @ManagedBean ,然后简单地 @Inject它在 Filter .

另请参阅:

关于jsf - 用于授权的RequestFilter和SessionBean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10880337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com