Part of my site should be accessible only to authorized users. Let's assume user would enter page a.html which belongs to the authorized-only part.
If I was to use servlets/JSP I could write a filter that checked whether user is logged in and if not - redirected him to login page. After a successful login user would be redirected to the page he wanted to reach initially, in this case a.html. (Page address could be开发者_C百科 stored in request).
What is a proper way to implement such scenario in JSF 2.0?
Just do it the same way, with a Filter
. It's good to know that JSF session scoped managed beans are under the covers stored as a HttpSession
attribute with the managed bean name as key.
Assuming that you've a managed bean like this:
@ManagedBean
@SessionScoped
public class UserManager {
private User user;
// ...
public boolean isLoggedIn() {
return (user != null);
}
}
Then you can check it in Filter#doFilter()
as follows:
UserManager userManager = (UserManager) ((HttpServletRequest) request).getSession().getAttribute("userManager");
if (userManager != null && userManager.isLoggedIn()) {
chain.doFilter(request, response);
} else {
((HttpServletResponse) response).sendRedirect("login.xhtml");
}
精彩评论