【发布时间】:2013-08-02 19:00:43
【问题描述】:
我需要在加载每个页面之前进行一些检查,看看是否需要将用户重定向到另一个页面(出于安全原因)。
当我使用 JSF 2.0 时,我使用了一个阶段监听器来完成这项工作。现在我使用的是 JSF 2.2,而且我所有的 bean 都不再是 JSF bean,而是 CDI bean,我认为我提供了更好的选择来执行此操作(或不执行此操作?)。
我听说过viewAction 事件,但我不想在每个页面上都重复元数据(除非没有其他选择)。
那么在 JSF 2.2 中使用 CDI 实现此场景的最佳方法是什么?
更新(在@skuntsel 建议之后)
这是我现在使用的过滤器。我只想在身份验证后使用它来简化它的代码。顺便说一句,如果您发现其中有任何错误,请告诉我。
@WebFilter("/*")
public class SolicitacoesFilter implements Filter
{
// I can't just use @Inject private User _user, because it needs to be initialized
// only when the user is authenticated. Otherwise an exception is thrown. If this
// filter was called only after the authentication I could use the mentioned code.
private User _user;
@Inject
private Instance<User> _userGetter;
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
if (initializeUser(request))
{
if (_user.isProvisoryPassword())
{
// Redirect to another page...
return;
}
if (_user.getStatus() != Status.ACTIVE)
{
// Redirect to another page...
return;
}
}
chain.doFilter(request, response);
}
@Override
public void destroy()
{
}
private boolean initializeUser(ServletRequest request)
{
boolean userAuthenticated = ((HttpServletRequest) request).getUserPrincipal() != null;
if (userAuthenticated)
{
if (_user == null)
{
_user = _userGetter.get();
}
}
else
{
_user = null;
}
return _user != null;
}
}
【问题讨论】:
-
在您提到的两个 JSF 版本中,Web 过滤器是首选方式!
-
我有一个代表用户的会话范围 CDI bean。我需要访问它才能进行检查。那么,我可以从过滤器中访问这个 CDI bean 吗?过滤器是否允许注入?
-
@WebFilter是通过@Inject对 CDI bean 的有效注入目标,但如果不是,数据当然可以通过 HTTP 会话的属性映射访问。相关:stackoverflow.com/questions/7815308/….