Logan
Logan

Reputation: 2515

Redirecting using jstl core Redirect

I want user to be redirected if the value I am checking in c:if is evaluated to true. For redirecting, I am using c:redirect url="url". But it is not redirecting me to the page. Here is the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<f:view>
<c:if test="#{user.loggedIn}">
    #{user.loggedIn}
    <c:redirect url="index.xhtml"></c:redirect>
</c:if>

    Hello #{user.name}

    <h:form>
    <h:commandButton value="Logout" action="#{user.logout}" />
    </h:form>
</f:view>

Here, h represents JSF Html Taglib, c is JSTL core taglib, f is JSF core taglib.

Upvotes: 2

Views: 7404

Answers (1)

BalusC
BalusC

Reputation: 1109532

Do not control the request/response in the view side. Do it in the controller side. Use a filter which you map on URL pattern of the restricted pages, such as /app/*. JSF session scoped managed beans are just available as HttpSession attributes in the filter.

@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);
    User user = (session != null) ? (User) session.getAttribute("user") : null;

    if (user == null || !user.isLoggedIn()) {
        response.sendRedirect("index.xhtml"); // No logged-in user found, so redirect to index page.
    } else {
        chain.doFilter(req, res); // Logged-in user found, so just continue request.
    }
}

The reason that this fails is that a JSF view is part of the response and that the response may already have been committed at that point. You should have seen an IllegalStateException: response already committed in the server logs at the point <c:redirect> is invoked.

Upvotes: 2

Related Questions