Using Servlet filter on all the pages except the index

喜你入骨 提交于 2020-01-06 02:43:51

问题


I'm trying to use a Filter to force my users to login if they want to access some pages.

So my Filter has to redirect them to an error page in there's no session.

But I don't want this to happen when they visit index.html, because they can login in the index page.

So I need an URL Pattern that matches all the pages excluding / and index.xhtml.

How can I do that? Can I use regex in my web.xml ?

EDIT:

After reading this

I thought that I can make something like :

if (!req.getRequestURI().matches("((!?index)(.*)\\.xhtml)|((.*)\\.(png|gif|jpg|css|js(\\.xhtml)?))"))

in my doFilter() method, but it still processes everything.

I'm sure that the regex works because I've tested it online and it matches the files that doesn't need to be filtered, but the content of the if is executed even for the excluded files!

EDIT 2 :

I'm trying a new way.

I've mapped the Filter to *.xhtml in my web.xml, so I don't need to exclude css, images and javascript with the regex above.

Here's the new code (into the doFilter())

if (req.getRequestURI().contains("index")) {
    chain.doFilter(request, response);
} else {
    if (!userManager.isLogged()) {
        request.getRequestDispatcher("error.xhtml").forward(request, response);
    } else {
        chain.doFilter(request, response);
    }
}

but it still doesn't because it calls the chain.doFilter() (in the outer if) on every page.

How can I exclude my index page from being filtered?


回答1:


The web.xml URL pattern doesn't support regex. It only supports wildcard prefix (folder) and suffix (extension) matching like /faces/* and *.xhtml.

As to your concrete problem, you've apparently the index file defined as a <welcome-file> and are opening it by /. This way the request.getRequestURI() will equal to /contextpath/, not /contextpath/index.xhtml. Debug the request.getRequestURI() to learn what the filter actually retrieved.

I suggest a rewrite:

String path = request.getRequestURI().substring(request.getContextPath().length());

if (userManager.isLogged() || path.equals("/") || path.equals("/index.xhtml") || path.startsWith(ResourceHandler.RESOURCE_IDENTIFIER)) {
    chain.doFilter(request, response);
} else {
    request.getRequestDispatcher("/WEB-INF/error.xhtml").forward(request, response);
}

Map this filter on /*. Note that I included the ResourceHandler.RESOURCE_IDENTIFIER check so that JSF resources like <h:outputStylesheet>, <h:outputScript> and <h:graphicImage> will also be skipped, otherwise you end up with an index page without CSS/JS/images when the user is not logged in.

Note that I assume that the FacesServlet is mapped on an URL pattern of *.xhtml. Otherwise you need to alter the /index.xhtml check on path accordingly.



来源:https://stackoverflow.com/questions/10708706/using-servlet-filter-on-all-the-pages-except-the-index

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