问题
As I was told and found on websites, my bean will only be executed if I have a call for it on my .xhtml
.
Is it possible to call my bean without any EL expression?
I need this because my HomeController
is calling a method that checks for the session status and on my home.xhtml
and don't have any need for fall this bean, for now.
回答1:
You need to look for a solution in a different direction.
If you're homegrowing user authentication instead of using container managed authentication, then you normally use a servlet filter for the particular purpose of checking if an user is logged in or not.
The servlet filter can like as servlets (like FacesServlet
) be mapped on a particular URL pattern. It will then be invoked on every request matching that URL pattern. You can explore request/session data in the filter and then handle the request/response accordingly by either continuning the filter chain, or by sending a redirect.
You need to implement javax.servlet.Filter interface accordingly. Here's a kickoff example of how the doFilter()
method should be implemented assuming that you've a @SessionScoped
managed bean LoginController
. JSF stores session scoped managed beans as attributes of HttpSession
.
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
LoginController loginController = (LoginController) (session != null) ? session.getAttribute("loginController") : null;
if (loginController == null || !loginController.isLoggedIn()) {
response.sendRedirect(request.getContextPath() + "/login.xhtml"); // No logged-in user found, so redirect to login page.
} else {
chain.doFilter(req, res); // Logged-in user found, so just continue request.
}
}
Map this filter on an URL pattern covering the restricted pages, e.g. /app/*
.
@WebFilter("/app/*")
public class LoginFilter implements Filter {
// ...
}
Update if the login.xhtml
is also covered by this URL pattern and you really can't change it, then change the if
block as follows:
if (!request.getRequestURI().endsWith("/login.xhtml") && (loginController == null || !loginController.isLoggedIn())) {
// ...
}
来源:https://stackoverflow.com/questions/10355131/how-to-provide-bean-methods-without-el-expression