我正在创建一个JSF应用程序,其中我在主页中嵌入了一个小程序。我的问题是,在将小程序加载到主页之前,我不知道如何检查会话是否存在,如果会话不存在,我想将用户重定向到主页
我建议使用过滤器:
public class LoggedFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpSession session = httpServletRequest.getSession(false);
if (session == null) {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(httpServletRequest.getContextPath() + "/"));
} else {
chain.doFilter(request, response);
}
}
当然,将这个过滤器映射到web.xml
:中的所有JSF页面
<filter>
<filter-name>LoggedFilter</filter-name>
<filter-class>LoggedFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoggedFilter</filter-name>
<url-pattern>*.xhtml</url-pattern>
</filter-mapping>
(我假设JSF页面有后缀xhtml)