Tamas
Tamas

Reputation: 23

JSF 2.0 Multiple requests generated per page

I have implemented a Filter for checking if a user is logged in or not by checking the session for a @SessionScoped bean. When I started testing it, I however, noticed that whenever I accessed one of my pages the Filter would be invoked multiple times.

I have figured out that I needed to ignore AJAX requests which reduced the number of times my filter would be invoked but the number of requests triggered each time I loaded the page was still more than one.

By trial and error, I have figured out that the requests would be generated by the following XHTML tags (both embedded in the <h:body> tag):

<h:outputStylesheet name="styles/userbar.css" target="head"/>
<o:commandScript name="updateMessages" render="custom_messages"/>

The second tag being part of OmniFaces library.

Any ideas why I get multiple requests or maybe if there is a way to ignore the requests generated by these tags?

Any help would be appreciated.

Upvotes: 2

Views: 999

Answers (1)

BalusC
BalusC

Reputation: 1108632

That can happen if you mapped the filter on a generic URL pattern like @WebFilter("/*"), or directly on the faces servlet like @WebFilter(servletNames="facesServlet"). The requests you're referring to are just coming from (auto-included) CSS/JS/image resources. If you track the browser's builtin HTTP traffic monitor (press F12, Network) or debug the request URI in filter, then that should have become clear quickly.

As to covering JSF resource requests, if changing the filter to listen on a more specific URL pattern like @WebFilter("/app/*") is not possible for some reason, then you'd need to add an additional check on the request URI. Given that you're using OmniFaces, you can use the Servlets utility class to check in a filter if the current request is a JSF ajax request or a JSF resource request:

@WebFilter("/*")
public class YourFilter extends HttpFilter {

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, HttpSession session, FilterChain chain) throws IOException, ServletException {
        if (Servlets.isFacesAjaxRequest(request) || Servlets.isFacesResourceRequest(request)) {
            chain.doFilter(request, response);
            return;
        }

        // ...
    }

}

See also:

Upvotes: 1

Related Questions