简体   繁体   中英

Servlet filter is called multiple times

I have a task to do some action (Pop up) on the web site if user visits site second time (any page). I decided to implement it with Servlet Filter + cookie. But I ran into the problem - filter calls multiple times, I think it related to using of tiles. Could you help me to fix it up? Or maybe somebody know the best practices for implementing this task.

Filter:

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    System.out.println("Do filter..............");

    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    String valueFromCookie = getCookieValue(request.getCookies(), EMAIL_POPUP_COOKIE);

    Cookie cookie = new Cookie(EMAIL_POPUP_COOKIE, "");
    cookie.setPath("/");
    cookie.setComment("Email Pop up cookie");
    cookie.setMaxAge(COOKIE_LIFE_TIME);

    if (valueFromCookie == null){
        String valueToCookie = URLEncoder.encode(FIRST_VISIT, "UTF-8");
        cookie.setValue(valueToCookie);
        response.addCookie(cookie);
    } else {
        if (valueFromCookie.equals(FIRST_VISIT)){
            String valueToCookie = URLEncoder.encode(NOT_SHOW, "UTF-8");
            cookie.setValue(valueToCookie);
            response.addCookie(cookie);
            System.out.println("STOP!=======================>");
        }
    }

    chain.doFilter(request, servletResponse);
}

web.xml part:

<filter-mapping>
    <filter-name>EmailPopUp</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

In case you are using JSF, it's important to be aware that different JSF components perform different combinations GET and POST requests when executed.

For instance:

  • <h:commandLink > performs both, a GET and a POST request when clicked
  • <h:link > performs only a GET request when clicked

If you are using a filter and you click a <h:commandLink > you will notice that the filter is called twice.
Additionally, remember that any type of request (ajax, resource, etc.) that matches the url pattern defined in web.xml, will pass through the filter so it will be called multiple times.

You can use browser developer tools to check which types and how many requests are being performed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM