Xhtml pages and HttpSession test , no jstl?
Asked Answered
D

1

1

I have a dynamic web application in Java EE with JSF, Facelets, Richfaces. My pages are all xhtml pages. So JSTL isn't working in it. For my account pages and all other private pages to be reachable, I want to test if the user got connected, so if the attribute session in HttpSession is not null. If it's null, the user gets redirected in the welcome page.

I tried in my xhtml page :

<jstl:if test="${sessionScope['session']==null}">
 <jstl redirect...>
</jstl:if>-->

but as it's not jsp page it won't work. So where am I supposed to test if the session is not null to allow the user to see his private pages ? in a central managed bean ?

Discreet answered 30/6, 2010 at 13:33 Comment(0)
F
3

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.

Finbur answered 30/6, 2010 at 14:46 Comment(1)
thank you very much... we've been suggested to do on each private page : <jstl:if test="${sessionScope['user']!=null}" > <jstl:redirect url=connexion.html" /> </jstl:if> but I prefered your method anyway, easy to maintain and more generic, thank you...Discreet

© 2022 - 2024 — McMap. All rights reserved.