我认为您可以为这种机制使用Java EE 过滤器。
过滤器由 Servlet 容器控制,并根据your web.xml
顺序首先在操作上运行。
将 servlet 过滤器添加到您的项目中。
public class YourFilter implements Filter {
public static final String USER = "USER_SESSION_KEY";
public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain)
{
HttpServletRequest request = (HttpServletRequest) req;
HttpSession session = request.getSession(true);
String servletpath = request.getServletPath();
if(!servletpath.contains("login.xhtml")) //exclude your login page and other pages required to pass this filter.
{
if (session.getAttribute(USER) != null)
{
//Control your authentication and roles.
}
else
{
//There is no user in the session.
}
}
}
filterChain.doFilter(request, response);
}
将您的过滤器添加到您的 web.xml
<filter>
<filter-name>YourFilter</filter-name>
<filter-class>Package.YourFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>YourFilter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
其次,将您的 User 类放到 JSF 操作中的会话中。
public void userAction()
{
User user = new User();
//Build your User Class
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
request.getSession(false).setAttribute("USER", user);
}
PS:用户类是用户定义的POJO类。你应该根据你的需要来实现它。
public class User
{
private String username;
//Other properties and getter setter methods required.
}
如果你想在 JSF 上下文中实现这个机制。您可以通过实现JSF 阶段侦听器来构建相同的逻辑。