Xhtml pages and HttpSession test , no jstl?

蓝咒 提交于 2019-12-03 21:38:37

The normal place for this is a Filter.

Create a class which implementsjavax.servlet.Filter and write the following logic in the doFilter() method:

if (((HttpServletRequest) request).getSession().getAttribute("user") == null) {
    // Not logged in, so redirect request to login page.
    ((HttpServletResponse) response).sendRedirect("/login.jsf");
} else {
    // Logged in, so just continue request.
    chain.doFilter(request, response);
}

Map this filter in web.xml on an url-pattern of something like /private/*, /secured/*, /restricted/*, etc.

<filter>
    <filter-name>loginFilter</filter-name>
    <filter-class>com.example.LoginFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>loginFilter</filter-name>
    <url-pattern>/private/*</url-pattern>
</filter-mapping>

If you have the private pages in the /private folder then this filter will be invoked and handle the presence of the logged-in user in the session accordingly.

Note that I renamed attribute name session to user since that makes much more sense. The HttpSession itself is namely already the session. It would otherise been too ambiguous and confusing for other developers checking/maintaining your code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!